将datagridview数据转换为excel后,我缺少列标题。在不同的指南中尝试了一些代码,但仍然没有得到标题,我缺少任何东西吗?
private void convert_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel.Worksheet worksheet = null;
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
worksheet.Name = "Unmatched";
for (int i = 1; i < dataGridView2.Columns.Count + 1; i++)
{
if (dataGridView2.Columns[i - 1].Visible)
{
worksheet.Cells[i, 1] = dataGridView2.Columns[i - 1].HeaderText;
}
}
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
for (int j = 0; j < dataGridView2.Columns.Count; j++)
{
if (dataGridView2.Rows[i].Cells[j].Value != null)
{
worksheet.Cells[i + 2, j + 1] = dataGridView2.Rows[i].Cells[j].Value.ToString();
}
}
}
var saveFileDialog = new SaveFileDialog();
saveFileDialog.FileName = "report";
saveFileDialog.DefaultExt = ".xlsx";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
workbook.SaveAs(saveFileDialog.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
}
app.Quit();
}
答案 0 :(得分:0)
worksheet.Cells[i] = dataGridView2.Columns[i - 1].HeaderText;