首页 > Windows开发 > 详细

C# 将DataTable里面的数据导出到excel

时间:2014-11-18 15:54:04      阅读:215      评论:0      收藏:0      [点我收藏+]

//需要在bin里面添加 Interop.Microsoft.Office.Interop.Excel.dll 的引用

//添加引用

using System.Data;

/// <summary>
/// 导出数据到Excel
/// </summary>
/// <param name="strWhere">查询条件</param>
/// <param name="returnMsg"></param>
/// <returns></returns>
public bool ExportOrderToExcel(string strWhere, ref string returnMsg)
  {
    try
      {
        DataTable dt = “DataTable 的数据集”;
          if (dt != null && dt.Rows.Count > 0)
            {
              int rowNumber = dt.Rows.Count;
              Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
              excel.Application.Workbooks.Add(true);
              excel.Visible = true;//是否打开该Excel文件
              //填充数据
              for (int c = 0; c <= rowNumber; c++) //行
              {
                for (int j = 0; j < 6; j++)//列
                {
                  if (c == 0) //表头
                  {
                    if (j == 0)
                    {
                      excel.Cells[c + 1, j + 1] = "";//表头名称
                    }
                    else if (...)
                    {
                      excel.Cells[c + 1, j + 1] = "";
                    }
                }
                else //填充内容
                {
                  excel.Cells[c + 1, j + 1] = dt.Rows[c-1][j];
                }
              }
            }
          returnMsg = "1,";//导出成功
          return true;
        }
      else
      {
        returnMsg = "2,没有查到要导出的数据!";
        return false;
      }
    }
    catch (Exception)
    {
      returnMsg = "2,导出数据失败!";
      return false;
    }
  }

C# 将DataTable里面的数据导出到excel

原文:http://www.cnblogs.com/a-mumu/p/4105964.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!