我有一个数据库应用程序,dataGridViews
上有多个Form
。我能够成功地将单个网格视图导出到Excel工作表,但我想将网格导出到单个Excel文件中的不同Excel工作表。
我尝试了以下哪些不起作用。
public void ExportGridViewToExcel(DataGridView dataGridViewCommission, DataGridView dataGridViewPaymentsReceived, string commissionsheet, string paymentsheet)
{
// 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 worksheet1 = null;
Microsoft.Office.Interop.Excel._Worksheet worksheet2 = null;
// see the excel sheet behind the program
// app.Visible = true;
// get the reference of first sheet. By default its name is Sheet1.
// store its reference to worksheet
worksheet1 = workbook.Sheets[1];
// changing the name of active sheet
worksheet1.Name = commissionsheet;
string filelocation;
SaveFileDialog SaveFile = new SaveFileDialog();
if (SaveFile.ShowDialog() == DialogResult.OK)
{
filelocation = SaveFile.FileName;
// storing header part in Excel
for (int i = 1; i < dataGridViewCommission.Columns.Count + 1; i++)
{
worksheet1.Cells[1, i + 1] = dataGridViewCommission.Columns[i - 1].HeaderCell.Value;
}
for (int i = 1; i < dataGridViewCommission.Rows.Count + 1; i++)
{
worksheet1.Cells[i + 1, 1] = dataGridViewCommission.Rows[i - 1].HeaderCell.Value;
//worksheet2.Cells[i + 1, 1] = dataGridViewPaymentsReceived.Rows[i - 1].HeaderCell.Value;
}
for (int i = 0; i < dataGridViewCommission.Rows.Count; i++)
{
for (int j = 0; j < dataGridViewCommission.Columns.Count; j++)
{
worksheet1.Cells[i + 2, j + 2] = dataGridViewCommission.Rows[i].Cells[j].Value.ToString();
}
}
worksheet2 = workbook.Sheets["Sheet2"];
worksheet2.Name = paymentsheet;
for (int i = 1; i < dataGridViewPaymentsReceived.Columns.Count + 1; i++)
{
worksheet2.Cells[1, i + 1] = dataGridViewPaymentsReceived.Columns[i - 1].HeaderCell.Value;
}
// storing Each row and column value to excel sheet
for (int i = 0; i < dataGridViewPaymentsReceived.Rows.Count; i++)
{
for (int j = 0; j < dataGridViewPaymentsReceived.Columns.Count; j++)
{
worksheet2.Cells[i + 2, j + 2] = dataGridViewPaymentsReceived.Rows[i].Cells[j].Value.ToString();
}
}
// save the application
workbook.SaveAs(filelocation, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
workbook.Close(true, Type.Missing, Type.Missing);
app.Quit();
Process.Start(filelocation + ".xls");
}
}
我遇到了COMexception
无效索引。 (来自HRESULT的异常:0x8002000B(DISP_E_BADINDEX))
任何人都可以建议我一个摆脱这个的方法吗?
答案 0 :(得分:1)
也许您需要先添加更多工作表,然后才能访问索引2处的工作表
int count = workbook.Worksheets.Count;
Excel.Worksheet addedSheet = workbook.Worksheets.Add(Type.Missing,
workbook.Worksheets[count], Type.Missing, Type.Missing);