如何将具有子列的表导出到Excel文件

本文关键字:文件 Excel | 更新日期: 2023-09-27 18:29:08

我有一个带有列a的表。在列a中有两个子列A1和A2。如何使用C#将表格导出到Excel文件?

如何将具有子列的表导出到Excel文件

如果你谈论的是数据网格视图,你可以这样做:

   public void ExportToExecl(DataGridView dg, string filename)
    {
         // creating Excel Application
        Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
        // creating new WorkBook within Excel application
        Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
        // creating new Excelsheet in workbook
        Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
        // get the reference of first sheet. By default its name is Sheet1.
        // store its reference to worksheet
        try
        {
            worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets["Sheet1"];
            worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.ActiveSheet;
            // changing the name of active sheet
            worksheet.Name = "Exported from History Parsing";
            // storing header part in Excel
            for (int i = 1; i < dg.Columns.Count + 1; i++)
            {
                worksheet.Cells[1, i] = dg.Columns[i - 1].HeaderText;
                worksheet.Cells[i + 2, j + 1].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Gray);
            }
            // storing Each row and column value to excel sheet
            for (int i = 0; i < dg.Rows.Count - 1; i++)
            {
                for (int j = 0; j < dg.Columns.Count; j++)
                {
                    worksheet.Cells[i + 2, j + 1] = dg.Rows[i].Cells[j].Value.ToString();
                    worksheet.Cells[i + 2, j + 1].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Gray);
                }
            }
            // save the application
            workbook.SaveAs(filename, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            MessageBox.Show("Your excel file was created successfully");
        }
        catch (System.Exception ex)
        {
        }
        finally
        {
            app.Quit();
            workbook = null;
            app = null;
        }
    }

你也可以在这里阅读关于导出dgv到excel的信息:

http://www.codeproject.com/Articles/28269/Exporting-a-DataGridView-to-an-Excel-PDF-image-fil

这里:

http://www.codeproject.com/Articles/43400/Generalized-DataGridView-Export-to-Excel-with-Them

  • 在编写代码之前,必须添加对Microsoft Excel对象库的引用。在项目上单击鼠标右键,然后选择"添加引用"菜单。然后转到COM选项卡,选择并添加Microsoft Excel 12.0对象库