gpt4 book ai didi

c# - 从 C# 导出到 Excel 不显示数据库中的第一行

转载 作者:行者123 更新时间:2023-11-29 18:39:40 24 4
gpt4 key购买 nike

我正在尝试将数据库c#导出到excel,但数据库的第一行是不保存在 Excel 中。

private void exporttoexcel()
{
Microsoft.Office.Interop.Excel._Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = excel.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;

try
{
worksheet = workbook.ActiveSheet;
worksheet.Name = "ExportedFromDatGrid";

int cellRowIndex = 1;
int cellColumnIndex = 1;

//Loop through each row and read value from each column.
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
// Excel index starts from 1,1. As first Row would have the Column headers, adding a condition check.
if (cellRowIndex == 1)
{
worksheet.Cells[cellRowIndex, cellColumnIndex] = dataGridView1.Columns[j].HeaderText;
}
else
{
worksheet.Cells[cellRowIndex, cellColumnIndex] = dataGridView1.Rows[i].Cells[j].Value.ToString();
}
cellColumnIndex++;
}
cellColumnIndex = 1;
cellRowIndex++;
}
}
catch(Exception ex)
{
}
}

here is the code I'm using. could anyone help me ? I am new in coding.

最佳答案

您不会写出数据,而只是在 cellColumnIndex 为 1 时写出列名称,跳过第一行。但在处理完第一行后,行索引增加。重构你的 for 循环,使其看起来像这样:

// Add the column names
var index = 0;
foreach(var column in dataGridView1.Columns)
{
worksheet.Cells[0, index] = column.HeaderText;
index++;
}

//Loop through each row and read value from each column.
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
// Excel index starts from 1,1. As first Row would have the Column headers, adding a condition check.
worksheet.Cells[cellRowIndex, cellColumnIndex] = dataGridView1.Rows[i].Cells[j].Value.ToString();
cellColumnIndex++;
}
cellColumnIndex = 1;
cellRowIndex++;
}

请查看ClosedXML 。它简化了代码编写,并且无需在要运行代码的计算机上安装 Excel。

关于c# - 从 C# 导出到 Excel 不显示数据库中的第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45031103/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com