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

时间:2013-08-26 03:47:25

标签: c# export-to-excel

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

1 个答案:

答案 0 :(得分:1)

如果您正在谈论数据网格视图,您可以这样做:

   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对象库