且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

简单的方法来DataGridView的导出到Excel

更新时间:2022-01-01 09:27:31

试试这个代码。它比正常的互操作方法快,也将其转换为CSV它可以很容易地用Excel读

Try this code. It's faster than the normal interop methods, also it converts into CSV which can be read easily by excel.

int cols;
//open file 
StreamWriter wr = new StreamWriter("GB STOCK.csv");

//determine the number of columns and write columns to file 
cols = dgvStock.Columns.Count;
for (int i = 0; i < cols - 1; i++)
{ 
    wr.Write(dgvStock.Columns[i].Name.ToString().ToUpper() + ",");
} 
wr.WriteLine();

//write rows to excel file
for (int i = 0; i < (dgvStock.Rows.Count - 1); i++)
{ 
    for (int j = 0; j < cols; j++)
    { 
        if (dgvStock.Rows[i].Cells[j].Value != null)
        {
            wr.Write(dgvStock.Rows[i].Cells[j].Value + ",");
        }
        else 
        {
            wr.Write(",");
        }
    }

    wr.WriteLine();
}

//close file
wr.Close();