简体   繁体   中英

How to export dataset to excel using CodeXml in C# Windows Application?

I got this Error :

System.TypeInitializationException was unhandled HResult=-2146233036 Message=The type initializer for 'ClosedXML.Excel.XLWorkbook' threw an exception. Source=ClosedXML TypeName=ClosedXML.Excel.XLWorkbook
StackTrace: at ClosedXML.Excel.XLWorkbook..ctor() at ClosedXml.Form1.ExportDataSetToExcel(DataSet ds) in c:\\users\\test\\documents\\visual studio 2010\\Projects\\ClosedXml\\ClosedXml\\Form1.cs:line 41 at ClosedXml.Form1.Form1_Load(Object sender, EventArgs e) in c:\\users\\test\\documents\\visual studio 2010\\Projects\\ClosedXml\\ClosedXml\\Form1.cs:line 30 at System.Windows.Forms.Form.OnLoad(EventArgs e) at System.Windows.Forms.Form.OnCreateControl() at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible) at System.Windows.Forms.Control.CreateControl() at System.Windows.Forms.Control.WmShowWindow(Message& m) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ScrollableControl.WndProc(Message& m) at System.Windows.Forms.Form.WmShowWindow(Message& m) at System.Windows.Forms.Form.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Form s.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) InnerException: System.IO.FileNotFoundException HResult=-2147024894 Message=Could not load file or assembly 'DocumentFormat.OpenXml, Version=2.0.5022.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified. Source=ClosedXML FileName=DocumentFormat.OpenXml, Version=2.0.5022.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 FusionLog==== Pre-bind state information === LOG: DisplayName = DocumentFormat.OpenXml, Version=2.0.5022.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 (Fully-specified) LOG: Appbase = file:///c:/users/test/documents/visual studio 2010/Projects/ClosedXml/ClosedXml/bin/Debug/ LOG: Initial PrivatePath = NULL Calling assembly : ClosedXML, Version=0.69.1.0, Culture=neutral, PublicKeyToken=fd1eb21b62ae805b. === LOG: This bind starts in default load context. LOG: No application configuration file found. LOG: Using host configuration file: LOG: Using machine configuration file from C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\config\\machine.config. LOG: Post-policy reference: DocumentFormat.OpenXml, Version=2.0.5022.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 LOG: Attempting download of new URL file:///c:/users/test/documents/visual studio 2010/Projects/ClosedXml/ClosedXml/bin/Debug/DocumentFormat.OpenXml.DLL. LOG: Attempting download of new URL file:///c:/users/test/documents/visual studio 2010/Projects/ClosedXml/ClosedXml/bin/Debug/DocumentFormat.OpenXml/DocumentFormat.OpenXml.DLL. LOG: Attempting download of new URL file:///c:/users/test/documents/visual studio 2010/Projects/ClosedXml/ClosedXml/bin/Debug/DocumentFormat.OpenXml.EXE. LOG: Attempting download of new 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:

And I am using the Code below:

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

您可以将ClosedXML NuGet 包的Version=0.69.1.0Version=0.69.1.0Version=0.94.2

You can also use another way to convert dataset to excel by using office API.

Code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM