如何在不使用FileDialog的情况下从DataGridView导出数据?

时间:2015-04-29 11:50:37

标签: c# datagridview export export-to-excel

我有一个名为Export Data的按钮。当我单击此按钮时,数据应默认存储在文件“abc.xls”中。

我能够存储数据但是当我第二次尝试存储值时,我得到了COMException。

有人能建议我吗?

我不想要一个锉刀。由于我使用的是默认文件,每次更改时都会覆盖该文件。提前致谢。

xlApp = new Microsoft.Office.Interop.Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = 
        (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
int i = 0;
int j = 0;
for (i = 0; i <= dataGridView1.RowCount - 1; i++)
 {
    for (j = 0; j <= dataGridView1.ColumnCount - 1; j++)
    {
      DataGridViewCell cell = dataGridView1[j, i];
      xlWorkSheet.Cells[i + 1, j + 1] = cell.Value;
    }
 }

xlWorkBook.SaveAs(@"C:\abc.xls", 
               Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, 
               misValue, misValue, misValue,
                 Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, 
                 misValue, misValue, misValue, misValue, misValue); 
                // A COMException is thrown here

 xlWorkBook.Close(true, misValue, misValue);
 xlApp.Quit();

 releaseObject(xlWorkSheet);
 releaseObject(xlWorkBook);
 releaseObject(xlApp);

1 个答案:

答案 0 :(得分:0)

说.xls和COMException,我怀疑你的意思是通过Excel COM自动化保存。然后,您将设置DisplayAlerts = false并使用SaveAs方法。即:

void Main()
{
    var f = new Form {Text = "Excel SaveAs sample"};
    var b = new System.Windows.Forms.Button {Text="Save as xls", AutoSize = true};
    var dgv = new DataGridView {Top=60};

    var tbl = new System.Data.DataTable();
    new SqlDataAdapter(
      "select CustomerId, CompanyName, ContactName from Customers", 
      @"server=.\SQLExpress;Database=Northwind;Trusted_Connection=yes")
      .Fill( tbl );

    dgv.DataSource = tbl;

    f.Controls.Add( b );
    f.Controls.Add( dgv );

    b.Click += (sender, args) => {
      var xl = new Microsoft.Office.Interop.Excel.Application();
      var wb = xl.Workbooks.Add();
      var sheet = (Worksheet)wb.ActiveSheet;

      for (int i = 0; i < dgv.Columns.Count; i++)
      {
        ((Range)sheet.Cells[1,i+1]).Value = dgv.Columns[i].HeaderText;
      }

      for (int i = 0; i < tbl.Rows.Count; i++)
      {
        for (int j = 0; j < tbl.Columns.Count; j++)
        {
          ((Range)sheet.Cells[i+2,j+1]).Value = dgv.Rows[i].Cells[j].Value.ToString();         
        }
      }
      xl.DisplayAlerts = false;
      wb.SaveAs(@"d:\temp\abc.xls");
      xl.Quit();
      MessageBox.Show("Saved");
    };

    f.Show();
}