【问题标题】:How to export dataset to excel using CodeXml in C# Windows Application?如何在 C# Windows 应用程序中使用 CodeXml 将数据集导出到 excel?
【发布时间】:2020-06-17 17:45:39
【问题描述】:

我收到了这个Error

System.TypeInitializationException 未处理 HResult=-2146233036 Message='ClosedXML.Excel.XLWorkbook' 的类型初始化器抛出了一个 例外。 Source=ClosedXML TypeName=ClosedXML.Excel.XLWorkbook
堆栈跟踪: 在 ClosedXML.Excel.XLWorkbook..ctor() 在 c:\users\test\documents\visual studio 中的 ClosedXml.Form1.ExportDataSetToExcel(DataSet ds) 2010\Projects\ClosedXml\ClosedXml\Form1.cs:第 41 行 在 c:\users\test\documents\visual studio 中的 ClosedXml.Form1.Form1_Load(Object sender, EventArgs e) 2010\Projects\ClosedXml\ClosedXml\Form1.cs:第 30 行 在 System.Windows.Forms.Form.OnLoad(EventArgs e) 在 System.Windows.Forms.Form.OnCreateControl() 在 System.Windows.Forms.Control.CreateControl(布尔 fIgnoreVisible) 在 System.Windows.Forms.Control.CreateControl() 在 System.Windows.Forms.Control.WmShowWindow(消息和 m) 在 System.Windows.Forms.Control.WndProc(消息和 m) 在 System.Windows.Forms.ScrollableControl.WndProc(消息和 m) 在 System.Windows.Forms.Form.WmShowWindow(消息和 m) 在 System.Windows.Forms.Form.WndProc(消息和 m) 在 System.Windows.Forms.Control.ControlNativeWindow.OnMessage(消息& m) 在 System.Windows.Forms.Control.ControlNativeWindow.WndProc(消息和 m) 在 System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd,Int32 msg,IntPtr wparam,IntPtr lparam)InnerException: System.IO.FileNotFoundException H结果=-2147024894 消息=无法加载文件或程序集'DocumentFormat.OpenXml,版本=2.0.5022.0,文化=中性, PublicKeyToken=31bf3856ad364e35' 或其依赖项之一。这 系统找不到指定的文件。 源=关闭XML 文件名=DocumentFormat.OpenXml,版本=2.0.5022.0,文化=中性,PublicKeyToken=31bf3856ad364e35 FusionLog==== 绑定前状态信息=== LOG: DisplayName = DocumentFormat.OpenXml, Version=2.0.5022.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35(完全指定)日志:Appbase = file:///c:/users/test/documents/visual studio 2010/Projects/ClosedXml/ClosedXml/bin/Debug/ 日志:初始 PrivatePath = NULL 调用程序集:ClosedXML,版本=0.69.1.0,文化=中性,PublicKeyToken=fd1eb21b62ae805b。 === LOG:此绑定在默认加载上下文中开始。 LOG:未找到应用程序配置文件。 LOG:使用主机配置文件:LOG: 使用来自的机器配置文件 C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config。 LOG:后策略参考:DocumentFormat.OpenXml, 版本=2.0.5022.0,文化=中性,PublicKeyToken=31bf3856ad364e35 日志:尝试下载新 URL file:///c:/users/test/documents/visual studio 2010/项目/ClosedXml/ClosedXml/bin/Debug/DocumentFormat.OpenXml.DLL。 日志:尝试下载新 URL file:///c:/users/test/documents/visual studio 2010/项目/ClosedXml/ClosedXml/bin/Debug/DocumentFormat.OpenXml/DocumentFormat.OpenXml.DLL。 日志:尝试下载新 URL file:///c:/users/test/documents/visual studio 2010/项目/ClosedXml/ClosedXml/bin/Debug/DocumentFormat.OpenXml.EXE。 日志:尝试下载新 URL file:///c:/users/test/documents/visual studio 2010/Projects/ClosedXml/ClosedXml/bin/Debug/DocumentFormat.OpenXml/DocumentFormat.OpenXml.EXE。

   StackTrace:
        at ClosedXML.Excel.XLWorkbook..cctor()
   InnerException:

我正在使用下面的代码:

private void Form1_Load(object sender, EventArgs e)
{
    DataSet ds = new DataSet();
    DataTable dt = new DataTable();
    dt.Columns.Add("Name");
    dt.Columns.Add("Country");
    dt.Rows.Add("Venkatesh", "India");
    dt.Rows.Add("Santhosh", "USA");
    dt.Rows.Add("Venkat Sai", "Dubai");
    dt.Rows.Add("Venkat Teja", "Pakistan");
    ds.Tables.Add(dt);
    ExportDataSetToExcel(ds);
}
public  void ExportDataSetToExcel(DataSet ds)
{
    string AppLocation = "";
    AppLocation = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase);
    AppLocation = AppLocation.Replace("file:\\", "");
    string date = DateTime.Now.ToShortDateString();
    date = date.Replace("/", "_");
    string filepath = AppLocation + "\\ExcelFiles\\" + "RECEIPTS_COMPARISON_" + date + ".xlsx";

    using (ClosedXML.Excel.XLWorkbook wb = new ClosedXML.Excel.XLWorkbook())
    {
        for (int i = 0; i < ds.Tables.Count; i++)
        {
             wb.Worksheets.Add(ds.Tables[i], ds.Tables[i].TableName);
        }
        wb.Style.Alignment.Horizontal = ClosedXML.Excel.XLAlignmentHorizontalValues.Center;
        wb.Style.Font.Bold = true;
        wb.SaveAs(filepath);
    }
}

【问题讨论】:

  • 我用0.94.2测试过,没有问题
  • 请给我codeXml.dll文件
  • PM&gt; Install-Package ClosedXML 兄弟github.com/ClosedXML/ClosedXML
  • @TấnNguyên 谢谢

标签: c# excel visual-studio


【解决方案1】:

您可以将ClosedXML NuGet 包的版本从Version=0.69.1.0 更新为Version=0.94.2

【讨论】:

  • 最新版ClosedXml如何下载
  • 在 Visual Studio 中使用控制台管理器或转到 NuGet 包管理器。
【解决方案2】:

您还可以通过office API 使用其他方式将数据集转换为excel。

代码:

    private void button1_Click(object sender, EventArgs e)
    {
        DataSet set = new DataSet();
        DataTable table1 = new DataTable();
        table1.TableName = "Student";
        table1.Columns.Add("Name");
        table1.Columns.Add("Id");
        table1.Columns.Add("Age");
        table1.Rows.Add("test1", 1001, 22);
        table1.Rows.Add("test2", 1005, 24);
        table1.Rows.Add("test3", 1007, 26);
        DataTable table2 = new DataTable();
        table2.TableName = "Product";
        table2.Columns.Add("ProductName");
        table2.Columns.Add("Date");
        table2.Columns.Add("Address");
        table2.Rows.Add("test1", "2020-01-01", "home");
        table2.Rows.Add("test2", "2020-02-01", "Company");
        table2.Rows.Add("test3", "2020-03-01", "School");
        set.Tables.Add(table1);
        set.Tables.Add(table2);
        ExportDataSetToExcel(set, "D:\\test.xlsx");
        MessageBox.Show("success");
    }
    private void ExportDataSetToExcel(DataSet ds, string path)
    {
        //Creae an Excel application instance
        Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
        //Create an Excel workbook instance and open it from the predefined location
        Microsoft.Office.Interop.Excel.Workbook excelWorkBook = excelApp.Workbooks.Add(Type.Missing);
        int count = 1;
        foreach (System.Data.DataTable table in ds.Tables)
        {
            //Add a new worksheet to workbook with the Datatable name
            Microsoft.Office.Interop.Excel.Worksheet excelWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelWorkBook.ActiveSheet;
            excelWorkSheet.Name = table.TableName;

            for (int i = 1; i < table.Columns.Count + 1; i++)
            {
                excelWorkSheet.Cells[1, i] = table.Columns[i - 1].ColumnName;
            }

            for (int j = 0; j < table.Rows.Count; j++)
            {
                for (int k = 0; k < table.Columns.Count; k++)
                {
                    excelWorkSheet.Cells[j + 2, k + 1] = table.Rows[j].ItemArray[k].ToString();
                }
            }
            if(count<ds.Tables.Count)
            {
                excelWorkBook.Sheets.Add(excelWorkSheet);
            }

            count++;
        }

        excelWorkBook.SaveAs(path);
        excelWorkBook.Close();
        excelApp.Quit();
    }

【讨论】:

  • 错误Excel cannot open the file 'test.xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.
  • 对不起,我已经更新了我的代码。根据我的测试,以上代码可以成功将数据集转换为excel。
猜你喜欢
  • 2016-03-24
  • 2023-03-17
  • 2016-07-05
  • 2011-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多