C#将datatable导出到excel

using System.IO;  
using Microsoft.Office.Core;  
using Excel = Microsoft.Office.Interop.Excel;

public bool ExportFile(System.Data.DataTable dt)
{
 SaveFileDialog sfd = new SaveFileDialog();
 sfd.Filter = "Excel文件(*.xls)|*.xls|所有文件(*.*)|*.*";
 sfd.Title = "Excel文件导出";
 string fileName = "";
 if (sfd.ShowDialog() == DialogResult.OK)
 {
  fileName = sfd.FileName;
  Excel.Application app = new Excel.Application();
  if (app == null)
  {
   MessageBox.Show("Excel启动失败!");
   return false;
  }
  try
  {
   app.Visible = false;
   Excel.Workbook xlWorkBook = app.Workbooks.Add(Type.Missing);
   Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
   int i;
   for (i = 0; i < dt.Columns.Count; i++)
   {
    xlWorkSheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
   }
   for (i = 0; i < dt.Rows.Count; i++)
   {
    for (int j = 0; j < dt.Columns.Count; j++)
    {
     xlWorkSheet.Cells[i + 2, j + 1] = dt.Rows[i][j].ToString();
    }
   }
   xlWorkBook.SaveAs(fileName, Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
   xlWorkBook.Close(true, Type.Missing, Type.Missing);
   app.Quit();

   ReleaseObject(xlWorkSheet);
   ReleaseObject(xlWorkBook);
   ReleaseObject(app);
   return true;
  }
  catch (System.Exception exc)
  {
   MessageBox.Show("excel运行错误:"+exc.Message);
   return false;
  }

 }
 else
 {
  return false;
 }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_老杨_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值