我有一个生成报告并显示在 datagridview 中的表单,当用户单击“导出到 Excel”时,datagridview 中的数据被传输到 excel 文件中。但我有问题:gridview的第一行没有保存在excel文件中请帮忙
提前致谢
下面是我使用的代码
if (dgvCreditLimitTransaction.RowCount >= 1)
{
// 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;
// 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
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
// changing the name of active sheet
worksheet.Name = "Transaction Details";
// storing header part in Excel
int hdinvdate = 0;
for (int i = 2; i <= dgvCreditLimitTransaction.ColumnCount; i++)
{
worksheet.Cells[1, i] = dgvCreditLimitTransaction.Columns[i - 1].HeaderText;
if (dgvCreditLimitTransaction.Columns[i - 1].HeaderText == "LC Number")
{
hdinvdate = i - 1;
}
}
// storing Each row and column value to excel sheet
for (int i = 0; i < dgvCreditLimitTransaction.Rows.Count; i++)
{
for (int j = 1; j < dgvCreditLimitTransaction.ColumnCount; j++)
{
if (dgvCreditLimitTransaction.Rows[i].Cells[j].Value != null)
{
if (j == hdinvdate)
{
DateTime tempinvdt = Convert.ToDateTime(dgvCreditLimitTransaction.Rows[i].Cells[j].Value);
worksheet.Cells[i + 2, j + 1] = tempinvdt.ToString("MM/dd/yyyy");
}
else
{
worksheet.Cells[i + 2, j + 1] = dgvCreditLimitTransaction.Rows[i].Cells[j].Value.ToString();
}
}
}
}
// Exit from the application
// app.Quit();
}
else
{
MessageBox.Show("Please select Data");
}