簡體   English   中英

如何從c#中的數據集或數據表導出excel?

[英]How to export excel from dataset or datatable in c#?

我想在不使用Gridview的情況下將數據從數據集或數據表導出到C#中的Excel文件。

我會推薦EPPlus - 這個解決方案不需要COM也不需要互操作,而且非常快。 非常適合Web場景。

http://epplus.codeplex.com/

http://nuget.org/packages/EPPlus

private void DumpExcel(DataTable tbl)
{
    using (ExcelPackage pck = new ExcelPackage())
    {
            //Create the worksheet
            ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");

            //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
            ws.Cells["A1"].LoadFromDataTable(tbl, true);

            //Format the header for column 1-3
            using (ExcelRange rng = ws.Cells["A1:C1"])
            {
                rng.Style.Font.Bold = true;
                rng.Style.Fill.PatternType = ExcelFillStyle.Solid;                      //Set Pattern for the background to Solid
                rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(79, 129, 189));  //Set color to dark blue
                rng.Style.Font.Color.SetColor(Color.White);
            }

            //Example how to Format Column 1 as numeric 
            using (ExcelRange col = ws.Cells[2, 1, 2 + tbl.Rows.Count, 1])
            {
                    col.Style.Numberformat.Format = "#,##0.00";
                    col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
                }

                //Write it back to the client
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("content-disposition", "attachment;  filename=ExcelDemo.xlsx");
                Response.BinaryWrite(pck.GetAsByteArray());
            }
        }
    }
}

獲取更多方法: 9將數據導出到Excel for ASP.NET的解決方案

我有這個代碼,但為此你需要包括Excel Com組件

在項目中添加Microsoft.Office.Interop.Excel.dll引用將為您完成任務。

using Excel = Microsoft.Office.Interop.Excel;
 public static bool ExportDataTableToExcel(DataTable dt, string filepath)
    {

    Excel.Application oXL;
    Excel.Workbook oWB;
    Excel.Worksheet oSheet;
    Excel.Range oRange;

    try
    {
        // Start Excel and get Application object. 
        oXL = new Excel.Application();

        // Set some properties 
        oXL.Visible = true;
        oXL.DisplayAlerts = false;

        // Get a new workbook. 
        oWB = oXL.Workbooks.Add(Missing.Value);

        // Get the Active sheet 
        oSheet = (Excel.Worksheet)oWB.ActiveSheet;
        oSheet.Name = "Data";

        int rowCount = 1;
        foreach (DataRow dr in dt.Rows)
        {
            rowCount += 1;
            for (int i = 1; i < dt.Columns.Count + 1; i++)
            {
                // Add the header the first time through 
                if (rowCount == 2)
                {
                    oSheet.Cells[1, i] = dt.Columns[i - 1].ColumnName;
                }
                oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
            }
        }

        // Resize the columns 
        oRange = oSheet.get_Range(oSheet.Cells[1, 1],
                      oSheet.Cells[rowCount, dt.Columns.Count]);
        oRange.EntireColumn.AutoFit();

        // Save the sheet and close 
        oSheet = null;
        oRange = null;
        oWB.SaveAs(filepath, Excel.XlFileFormat.xlWorkbookNormal,
            Missing.Value, Missing.Value, Missing.Value, Missing.Value,
            Excel.XlSaveAsAccessMode.xlExclusive,
            Missing.Value, Missing.Value, Missing.Value,
            Missing.Value, Missing.Value);
        oWB.Close(Missing.Value, Missing.Value, Missing.Value);
        oWB = null;
        oXL.Quit();
    }
    catch
    {
        throw;
    }
    finally
    {
        // Clean up 
        // NOTE: When in release mode, this does the trick 
        GC.WaitForPendingFinalizers();
        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();
    }

    return true;
}

以防其他人使用所選解決方案並遇到“對象不包含get_Range的定義”異常。 我在這里找到了解決方案: 工作表get_Range拋出異常 我希望這會節省你的時間。

您可以使用

using Microsoft.Office.Interop.Excel;

使用excel文檔“本機”...

使用C#創建Excel文檔http://www.codeproject.com/Articles/20228/Using-C-to-Create-an-Excel-Document

但是,如果您使用的是SQL SERVER,大多數常見的報告生成器/設計器都可以輕松導出到excel,還可以檢查Reporting Services

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM