C# 如何将具有子列的表导出到Excel文件?
我有一个表,有一列a。在a列中有两个子列,A1和A2。如何使用C#?将表格导出到Excel文件如果您谈论的是数据网格视图,则可以执行以下操作:C# 如何将具有子列的表导出到Excel文件?,c#,export-to-excel,C#,Export To Excel,我有一个表,有一列a。在a列中有两个子列,A1和A2。如何使用C#?将表格导出到Excel文件如果您谈论的是数据网格视图,则可以执行以下操作: public void ExportToExecl(DataGridView dg, string filename) { // creating Excel Application Microsoft.Office.Interop.Excel._Application app = new Microsof
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;
}
}
public void ExportToExecl(DataGridView dg,字符串文件名)
{
//创建Excel应用程序
Microsoft.Office.Interop.Excel.\u应用程序app=新的Microsoft.Office.Interop.Excel.Application();
//在Excel应用程序中创建新工作簿
Microsoft.Office.Interop.Excel.\u工作簿=app.Workbooks.Add(Type.Missing);
//在工作簿中创建新的Excel工作表
Microsoft.Office.Interop.Excel.\u工作表=null;
//获取第一张图纸的引用。默认情况下,其名称为Sheet1。
//将其引用存储到工作表
尝试
{
工作表=(Microsoft.Office.Interop.Excel.worksheet)workbook.Sheets[“Sheet1”];
工作表=(Microsoft.Office.Interop.Excel.worksheet)workbook.ActiveSheet;
//更改活动图纸的名称
worksheet.Name=“从历史解析导出”;
//在Excel中存储标题部分
对于(int i=1;i
您还可以在此处阅读有关将dgv导出到excel的信息:
在这里:
- 在编写代码之前,必须添加对Microsoft Excel对象库的引用。 在项目上单击鼠标右键,然后选择“添加引用”菜单。然后转到COM选项卡,选择并添加Microsoft Excel 12.0对象库