简体   繁体   English

从c#导出到excel不显示数据库的第一行

[英]export to excel from c# is not showing first row from database

I am trying to export a database from c# to excel but the first row from the database is not saving in 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)
   {
   }
}

here is the code I'm using. 这是我正在使用的代码。 could anyone help me ? 有人可以帮我吗? I am new in coding. 我是编码新手。

You're not writing out the data but are only writing out column names when the cellColumnIndex is 1, skipping the first row. 您不会写出数据,而是仅在cellColumnIndex为1时写出列名,跳过第一行。 But after the first row has been processed, the row index will be incremented. 但是在处理完第一行后,行索引增加。 Refactor your for-loop to look something like this: 重构您的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++;
}

Please have a look at ClosedXML . 请看看ClosedXML It simplifies writing your code, and eliminate the need to have Excel installed on the machine where you want to run this. 它简化了代码编写,并消除了在要运行此代码的计算机上安装Excel的需求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM