我正在创建一个将数据导出DataGridView
到 Excel 文件的类。当我调用该方法时,我得到了一个空的 Excel 表。但是,当我直接在代码中插入方法而不使用类时,它确实有效。
知道为什么这个类不起作用。
class ExportToExcel
{
public Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application();
public Microsoft.Office.Interop.Excel._Workbook ExcelBook;
public Microsoft.Office.Interop.Excel._Worksheet ExcelSheet;
DataGridView dt = new DataGridView();
public DataGridView Dt { set { this.dt = value; } }
public Microsoft.Office.Interop.Excel.Application exportToExcel(DataGridView dt)
{
int i = 0;
int j = 0;
ExcelBook = (Microsoft.Office.Interop.Excel._Workbook)ExcelApp.Workbooks.Add(1);
ExcelSheet = (Microsoft.Office.Interop.Excel._Worksheet)ExcelBook.ActiveSheet;
//export header
for (i = 1; i <= this.dt.Columns.Count; i++)
{
ExcelSheet.Cells[1, i] = this.dt.Columns[i - 1].HeaderText;
}
//export data
for (i = 1; i <= this.dt.RowCount; i++)
{
for (j = 1; j <= dt.Columns.Count; j++)
{
ExcelSheet.Cells[i + 1, j] = dt.Rows[i - 1].Cells[j - 1].Value;
}
}
ExcelApp.Visible = true;
ExcelSheet = null;
ExcelBook = null;
ExcelApp = null;
return ExcelApp;
}
}
private void exportToExcel_Click(object sender, EventArgs e)
{
ExportToExcel ex = new ExportToExcel();
ex.exportToExcel(dtReport2);
}