using System;
using System.IO;
using System.Data;
using System.Reflection;
using System.Diagnostics;
using System.Configuration;
using System.Collections;
using Excel;

namespace thscjy
{
 ///
 /// 套用模板输出Excel,生成xls文件和html文件
 /// Author: Liu Wen
 /// Date Created: 2006-8
 ///
 public class ExportExcel
 {
  #region variable member 成员变量
  protected string templateFile = null;
  protected string excelFile = null;
  protected string htmlFile = null;
  protected object missing = Missing.Value;
  Excel.ApplicationClass app;
  Excel.Workbook book;
  Excel.Worksheet sheet;
  Excel.Range range;
  private DateTime beforeTime;  //Excel启动之前时间
  private DateTime afterTime;  //Excel启动之后时间
  //private int processID;
  #endregion

///
  /// 构造函数,将一个已有Excel工作簿作为模板,并指定输出路径
  ///
  /// Excel模板文件路径
  /// Excel输出文件路径
  /// Html输出文件路径
  public ExportExcel(string templateFile, string excelFile, string htmlFile)
  {
   if (templateFile == null)
    throw new Exception("Excel模板文件路径不能为空!");

if (excelFile == null)
    throw new Exception("Excel输出文件路径不能为空!");

if (htmlFile == null)
    throw new Exception("Html输出文件路径不能为空!");

if (!File.Exists(templateFile))
    throw new Exception("指定路径的Excel模板文件不存在!");

this.templateFile = templateFile;
   this.excelFile = excelFile;
   this.htmlFile = htmlFile;

//创建一个Application对象
   beforeTime = DateTime.Now;
   app = new ApplicationClass();
   //app.Visible = true;
   //processID = Process.GetCurrentProcess().Id;
   afterTime = DateTime.Now;

//打开模板文件,得到WorkBook对象
   try
   {
    book = app.Workbooks.Open(templateFile,missing,missing,missing,missing,missing,
     missing,missing,missing,missing,missing,missing,missing,missing,missing);
   }
   catch (Exception e)
   {
    throw e;
   }
   //得到WorkSheet对象
   sheet = (Excel.Worksheet)book.Sheets.get_Item(1);
  }

#region 插入报表参数
  ///
  /// 录入报表的参数(TJ统计用)
  ///
  /// 填报单位
  /// 年月
  /// 填报人
  /// 填报日期
  /// 插入数据的单元格
  public void InsertArgs(string department, string date, string accountant, string dateCreated, string cellID)
  {
   sheet.get_Range("A3", missing).Value2 = "填报单位:"+department;
   sheet.get_Range("D3", missing).Value2 = date;
   sheet.get_Range(cellID, missing).Value2 = "部门负责人:       填报人:"+accountant+" 联系电话:                 报送时间:"+dateCreated;
   //sheet.get_Range("I8", missing).Value2 = "填报日期:"+dateCreated;
  }

///
  /// 录入报表的参数(JH计划用)
  ///
  /// 标题
  public void InsertArgsJH(string name)
  {
   sheet.get_Range("A1", missing).Value2 = name;
  }

///
  /// 录入报表的参数(JH计划用)
  ///
  /// 标题
  /// 年份
  public void InsertArgsJH(string name, string year)
  {
   sheet.get_Range("A1", missing).Value2 = name;
   sheet.get_Range("D2", missing).Value2 = year;
  }

///
  /// 录入报表的参数(JH计划用)
  ///
  /// 标题
  /// 部门
  /// “部门”单元格ID
  /// 年份
  /// “年份”单元格ID
  public void InsertArgsJH(string name, string department, string depCellId, string year, string yearCellId)
  {
   sheet.get_Range("A1", missing).Value2 = name;
   sheet.get_Range(depCellId, missing).Value2 = department;
   sheet.get_Range(yearCellId, missing).Value2 = year;
  }

///
  /// 录入报表的参数(JH计划用)
  ///
  /// 标题
  /// 注水
  /// 注气
  /// 措施工作量
  public void InsertArgsJH(string name, string water, string gas, string workload)
  {
   sheet.get_Range("A1", missing).Value2 = name;
   sheet.get_Range("C2", missing).Value2 = water;
   sheet.get_Range("E2", missing).Value2 = gas;
   sheet.get_Range("G2", missing).Value2 = workload;
  }
  #endregion

#region 导出Excel方法

///
  /// 将DataTable数据导出到Excel(可动态插入行)
  ///
  /// DataTable
  /// 插入行的索引
  /// 插入列的索引
  public void DataTableToExcel(System.Data.DataTable dt, int rowIndex, int colIndex)
  {
   int rowCount = dt.Rows.Count;  //DataTable行数
   int colCount = dt.Columns.Count; //DataTable列数
   int iRow;
   int iCol;

//将数据导出到相应的单元格
   for (iRow = 0; iRow < rowCount; iRow++)
   {
    //插入新行
    this.InsertRows(sheet, iRow+rowIndex);
    //填充当前行
    for (iCol = 0; iCol < colCount; iCol++)
    {
     sheet.Cells[iRow+rowIndex, iCol+colIndex] = dt.Rows[iRow][iCol].ToString();
    }
   }
   this.DeleteRows(sheet, rowCount+rowIndex);

//this.OutputFile();

//Excel.QueryTables qts = sheet.QueryTables;
   //Excel.QueryTable qt = qts.Add(,,);
   //qt.RefreshStyle = Excel.XlCellInsertionMode.xlInsertEntireRows;
   //qt.Refresh();
  }

///
  /// 将DataTable数据导出到Excel(可动态插入行)
  ///
  /// DataTable
  /// 插入数据的起始单元格
  public void DataTableToExcel(System.Data.DataTable dt, string cellID)
  {
   int rowIndex = sheet.get_Range(cellID, missing).Row;
   int colIndex = sheet.get_Range(cellID, missing).Column;
   int rowCount = dt.Rows.Count;  //DataTable行数
   int colCount = dt.Columns.Count; //DataTable列数
   int iRow;
   int iCol;

//利用二维数组批量写入
   string[,] array = new string[rowCount,colCount];
   for (iRow = 0; iRow < rowCount; iRow++)
   {
    for (iCol = 0; iCol < colCount; iCol++)
    {
     array[iRow,iCol] = dt.Rows[iRow][iCol].ToString();
    }
   }

for (iRow = 0; iRow < rowCount; iRow++)
   {
    this.InsertRows(sheet, iRow+rowIndex);
   }
   this.DeleteRows(sheet, rowCount+rowIndex);

range  = sheet.get_Range(cellID, missing);
   range = range.get_Resize(rowCount, colCount);
   range.Value2 = array;
  }

///
  /// 将DataTable数据导出到Excel(固定)
  ///
  /// DataTable
  /// 插入数据的起始单元格
  public void DataTableToExcel2(System.Data.DataTable dt, string cellID)
  {
   int rowCount = dt.Rows.Count;  //DataTable行数
   int colCount = dt.Columns.Count; //DataTable列数
   int iRow;
   int iCol;

//利用二维数组批量写入
   string[,] array = new string[rowCount,colCount];
   for (iRow = 0; iRow < rowCount; iRow++)
   {
    for (iCol = 0; iCol < colCount; iCol++)
    {
     array[iRow,iCol] = dt.Rows[iRow][iCol].ToString();
    }
   }

range  = sheet.get_Range(cellID, missing);
   range = range.get_Resize(rowCount, colCount);
   range.Value2 = array;
  }
  #endregion

///
  /// 最后调用,释放相关资源,完成
  ///
  public void Finalize()
  {
   this.OutputFile();
   GC.Collect();
   //this.KillExcelProcess();
  }

///
  /// 输出生成的Excel, Html文件
  ///
  private void OutputFile()
  {
   //如果文件已存在,删除,重新生成
   if (File.Exists(excelFile))
   {
    File.Delete(excelFile);
   }
   if (File.Exists(htmlFile))
   {
    File.Delete(htmlFile);
   }
   try
   {
    book.SaveAs(excelFile, missing, missing, missing, missing, missing,
     Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing,missing);

book.SaveAs(htmlFile, Excel.XlFileFormat.xlHtml, missing, missing, missing, missing,
     Excel.XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing);
   }
   catch (Exception e)
   {
    throw e;
   }
   finally
   {
    this.Dispose();
   }
  }

///
  /// 在工作表中插入行,并调整其他行以留出空间
  ///
  /// 当前工作表
  /// 欲插入的行索引
  private void InsertRows(Excel.Worksheet sheet, int rowIndex)
  {
   range = (Excel.Range)sheet.Rows[rowIndex, missing];  
   //object Range.Insert(object shift, object copyorigin);
   //shift: Variant类型,可选。指定单元格的调整方式。可以为下列 XlInsertShiftDirection 常量之一:
   //xlShiftToRight 或 xlShiftDown。如果省略该参数,Microsoft Excel 将根据区域形状确定调整方式。
   range.Insert(Excel.XlInsertShiftDirection.xlShiftDown, missing);  
  }

///
  /// 在工作表中删除行
  ///
  /// 当前工作表
  /// 欲删除的行索引
  private void DeleteRows(Excel.Worksheet sheet, int rowIndex)
  {
   range = (Range)sheet.Rows[rowIndex, missing];
   range.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);
  }

///
  /// 退出Excel,并且释放调用的COM资源
  ///
  private void Dispose()
  {
   book.Close(missing, missing, missing);
   app.Workbooks.Close();
   app.Quit();

if (range != null)
   {
    System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
    range = null;
   }
   if (sheet != null)
   {
    System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
    sheet = null;
   }
   if (book != null)
   {
    System.Runtime.InteropServices.Marshal.ReleaseComObject(book);
    book = null;
   }
   if (app != null)
   {
    System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
    app = null;
   }

//System.GC.Collect();
   //GC.WaitForPendingFinalizers();
   //this.KillExcelProcess();
   //Process pro = Process.GetProcessById(processID);
   //pro.Kill();
  }

///
  /// 结束Excel进程
  ///
  private void KillExcelProcess()
  {
   DateTime startTime;
   Process[] processes = Process.GetProcessesByName("Excel");

//得不到Excel进程ID,暂时只能判断进程启动时间
   foreach (Process process in processes)
   {
    startTime = process.StartTime;
    if(startTime > beforeTime && startTime < afterTime)
    {
     process.Kill();
    }
   }
  }

}
}

DataSet导出到Excel,并生成文件(C#实现,可合并行和列)的更多相关文章

  1. asp.net教程:GridView导出到Excel或Word文件

    asp.net教程:GridView导出到Excel或Word文件</ br> 在项目中我们经常会遇到要求将一些数据导出成Excel或者Word表格的情况,比如中国移动(我是中国移动用户) ...

  2. .net DataSet 导出到Excel

    public void CreateExcel(DataSet ds, string typeid, stringFileName)        {           HttpResponse r ...

  3. 【C#】Excel导出合并行和列并动态加载行与列

    简单的Excel导出比较好做,只要设置表头,循环在表格中赋值添加数据即可,但是如果表头是不固定的,并且个数是不确定的,这就需要根据查询出数据的特点来添加导出了. 导出效果图: 如上图所示,商品的个数是 ...

  4. DataSet导出到Excel文件

    public static void ExportToExcel(DataSet source, string fileName) { System.IO.StreamWriter excelDoc ...

  5. dataset导出成excel

    之前网上查找了很多关于这类的代码.要不是中文乱码,要不是就是太复杂.这个是我用过最好用的. //ds为数据源,filename为保存的文件名 publicvoidCreateExcel(DataSet ...

  6. ASP.NET用DataSet导出到Excel

    //读取临时文件    GYYW.DA.Common.Base_SqlDataBase daBZDM = new GYYW.DA.Common.Base_SqlDataBase();    DataS ...

  7. .Net 中DataSet导出为excel的方法

    依旧是留下代码防止以后忘记 protected void Export_Click(object sender, EventArgs e) { DataSet data = "" ...

  8. laravel 导出导入excel和csv文件的 使用

    在项目中用到的常用功能数据导入导出 在laravel有插件可以直接使用 方便快捷 学习源头: https://www.cnblogs.com/martianShu/p/5869270.html htt ...

  9. pandas 读写excel 操作(按索引和关键字读取行和列,写入csv文件)

    pandas读写excel和csv操作总结 按索引读取某一列的值 按关键字读取某一列的值 按关键字查询某一行的值 保存成字典并写入新的csv import pandas as pd grades=pd ...

随机推荐

  1. 几组User-Agent

    Your User Agent String is: Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.19 (KHTML, like Gecko) Ubun ...

  2. 在GridView中使用radioButoon

    在GridView中使用radioButoon 方法一: <input type="radio" id='radioSelectFeed' name="radioD ...

  3. c++中的##和#的区别

    ##是一个连接符号,用于把参数连在一起 #是“字符串化”的意思.出现在宏定义中的#是把跟在后面的参数转换成一个字符串 #define paster( n ) printf( "token & ...

  4. 基情四射的两个css样式

    自定义blog样式时,代码段的line-height继承样式post的line-height,间隔太大了,决定再减小点,css都玩了几年了,感觉中这是很容易的事情.然后,就悲剧了好久,原先自定义样式表 ...

  5. 精选29款非常实用的jQuery应用插件

    今天我们来分享一些实用的jQuery应用插件,没有特别花哨,但都比较实用,jQuery菜单.jQuery图片都有涉及到,一起来看看. 1.jQuery+CSS3仿IOS无线局域网Wifi DEMO演示 ...

  6. windows7 中开启无线热点

    我用的是移动的 CMCC-EDU 上网,但是这个只能在一个设备上登陆,那么问题就来了,当我电脑需要用网,手机也想要用网(不用 2/3/4G)该怎么办? 电脑操作系统:windows7 接下来是开启 w ...

  7. Python Django 开发 2 数据库

    一半教程用的Django都是1.8以前的版本,导致跟我用的1.8.2的版本用法有些出入,所以只能自己去官网看文档,以下一下是看官方文档而理解的,英语渣渣,可能会有理解有误的地方 先记录下如何查看dja ...

  8. 【原创】MYSQL++源码剖析——前言与目录

    终于完成了! 从第一次想写到现在真的写好大概花了我3个月时间.原来一直读人家的系列文章,总感慨作者的用心良苦和无私奉献,自己在心里总是会觉得有那么些冲动也来写一个. 最开始的麻烦是犹豫该选哪个主题.其 ...

  9. Javascript this 关键字

    Javascript 的 this 关键字总是指向当前被执行函数的所有者. 换句话说,如果当前函数可以视为某个对象的一个方法,那么 this 就指向该对象. 例如有这么一个函数 doSomething ...

  10. 12306外包给阿里巴巴/IBM到底是否可行?

    春运开始以后 12306 免不了要罢工几次,毕竟人民群众买票回家的热情实在是高涨,12306 很难承受如此大的压力.每次 12306 网站罢工以后都会有人忍不住对其进行吐槽,而还有人认为如果把 123 ...