【发布时间】:2012-03-30 04:57:39
【问题描述】:
我试图在 Winforms 应用程序中使用 Visual Studio 2010 在 C# 中将 datagridview 导出到 excel(.xls),问题是它需要永远保存,到目前为止我有 4220 行和 20 列。有没有更快的方法来做到这一点。注意:我正在从保存的 excel 文件中填充 datagridview。感谢您的帮助....我的保存代码如下:
private void btnSave_Click(object sender, EventArgs e)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
// Get the Header from dataGridView
for (int h = 1; h < dataGridView1.Columns.Count + 1; h++)
{
xlWorkSheet.Cells[1, h] = dataGridView1.Columns[h - 1].HeaderText;
}
// Get the Cell Values
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
DataGridViewCell cell = dataGridView1[j, i];
xlWorkSheet.Cells[i + 2, j + 1] = cell.Value;
}
}
//xlWorkBook.SaveCopyAs("\\FORM TEST.xlsx");
xlWorkBook.SaveAs("\\GB STOCK.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
xlApp = null;
xlWorkBook = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
【问题讨论】:
标签: c# excel datagridview export-to-excel