【问题标题】:How to export excel from dataset or datatable in c#?如何从 C# 中的数据集或数据表中导出 excel?
【发布时间】:2014-02-28 01:50:39
【问题描述】:

我想在不使用 Gridview 的情况下将数据集或数据表中的数据导出到 C# 中的 Excel 文件。

【问题讨论】:

  • @Pankaj:编辑时,请删除“请”、“谢谢”等类似情绪。我们的目标是简短而甜蜜。 :)

标签: c# export-to-excel


【解决方案1】:

我会推荐 EPPlus - 此解决方案不需要 COM 或互操作 dll,而且速度非常快。非常适合网络场景。

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());
            }
        }
    }
}

【讨论】:

    【解决方案2】:

    获取更多途径:9 Solutions to Export Data to 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;
    }
    

    【讨论】:

    • 我们可以手动处理数据表和其他excel对象,而不是显式调用GC吗?通过调用相应的 dispose 函数?
    • 通过调用 dispose 函数,这会将对象发送到 GC Queue,而不是让 GC 找出哪个对象有资格进行 dispose。
    • 使用 COM 速度慢,需要在服务器上安装 Excel。每次生成电子表格时,都必须启动 Excel 流程。您最终可能会在 Web 服务器上运行多个 Excel 进程。另外,您需要许可证。
    • @JakubKonecki - 同意这一点最快的方法是利用数据网格导出到 excel
    • 这成功了。但是现在我不断收到这个错误“'object'不包含'get_Range'的定义”我试图设置范围,我也尝试过这样做stackoverflow.com/questions/6546785/...但我仍然无法保存文件。你有什么想法吗?
    【解决方案3】:

    你可以使用

    using Microsoft.Office.Interop.Excel;
    

    使用“本机”excel文档...

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

    但大多数常见的报表生成器/设计器都可以轻松导出到 excel 如果您使用的是 SQL SERVER

    ,还要检查 Reporting Services

    【讨论】:

      【解决方案4】:

      以防万一其他人使用了所选的解决方案并遇到“对象不包含 get_Range 的定义”异常。我在这里找到了解决方案:Worksheet get_Range throws exception。我希望这会节省您的时间。

      【讨论】:

        猜你喜欢
        • 2011-09-02
        • 1970-01-01
        • 2012-06-25
        • 2010-10-21
        • 2021-12-23
        • 1970-01-01
        • 2019-12-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多