从c#导出到excel并未显示数据库

时间:2017-07-11 09:50:53

标签: c# mysql database excel export-to-excel

我正在尝试将 数据库 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)
   {
   }
}
  

这是我正在使用的代码。谁能帮助我?我是编码新手。

1 个答案:

答案 0 :(得分:0)

您没有写出数据,只是在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。