我已经将数据从grivdview导出到excel文件,现在我想通过代码将其直接保存在桌面上,该怎么办?

时间:2019-12-12 12:32:49

标签: c#

private void button1_Click(object sender, EventArgs e)
{
     Microsoft.Office.Interop.Excel.Application Excel = new Microsoft.Office.Interop.Excel.Application();
     Workbook wb = Excel.Workbooks.Add(XlSheetType.xlWorksheet);
     Worksheet ws = (Worksheet)Excel.ActiveSheet;
     Excel.Visible = true;            

     for (int i=1;i<dataGridView1.Columns.Count+1;i++)
     {
          ws.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
     }
     for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
     { 
          for(int j=0;j<dataGridView1.Columns.Count;j++)
          {
              ws.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
          }
     }

1 个答案:

答案 0 :(得分:1)

using CsvHelper;

public void Export()
{
    using (var writer = new StreamWriter(Path.Combine(pathToExportData, filename)))
        using (var csv = new CsvWriter(writer))
        {
            csv.WriteRecords(dataListToExport);
        }
}