我有一个带有 A 列的表。在 A 列中有 2 个子列 A1 和 A2。如何使用 C# 将表格导出到 Excel 文件?
问问题
477 次
1 回答
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 对象库
于 2013-08-26T05:33:30.970 回答