在项目引用中添加Excel
//类文件中添加命名空间,读写Excel2003版本
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Excel;
namespace ***
{
/// <summary>
/// Report类
/// </summary>
public class Report
{
/// <summary>
/// 创建Excel实例
/// </summary>
private Excel.Application ExcelApp = new Excel.ApplicationClass();
private Excel.Workbook ExcelDoc;
private Excel.Worksheet ws;
private Object Nothing = System.Reflection.Missing.Value;
int Qulaity=0;
private bool _isPrint = true;
/// <summary>
/// 是否打印
/// </summary>
public bool IsPrint
{
get { return _isPrint; }
set { _isPrint = value; }
}
/// <summary>
/// 读指定路径中的Excel文件
/// </summary>
/// <param name="path">路径</param>
public void ReadExcel(string path)
{
ExcelDoc = ExcelApp.Workbooks.Add(path);
ws = (Excel.Worksheet)ExcelDoc.Sheets[1];
//Range类
Excel.Range range;
//以第二行,第三列单元格为例
range = (Excel.Range)ws.Cells[2, 3];
Qulaity = int.Parse(range.Value2.ToString());
//读完关闭Excel并退出
ExcelDoc.Close(Nothing, path, Nothing);
ExcelApp.Quit();
}
/// <summary>
/// 写Excel
/// </summary>
/// <param name="dt">System.Data.DataTable类实例</param>
/// <param name="sn">要保存的SN</param>
public void WriteModule(System.Data.DataTable dt,string sn)
{
//可以添加一个指定的Excel文件作为模板,往里写数据
//也可以指定一个Nothing,空Excel文件
ExcelDoc = ExcelApp.Workbooks.Add(Nothing);
ws = (Excel.Worksheet)ExcelDoc.Sheets[1];
DataRow dr ;
int rowcount = 0;
while (rowcount < dt.Rows.Count)
{
dr = dt.Rows[rowcount];
int j = 0;
//将日期写入单元格F2
ws.Cells[2, "F"] = dr["日期"].ToString();
//保存文件
ExcelDoc.SaveAs(@"D:\****\" + dr["SN"].ToString(), Nothing, Nothing, Nothing, Nothing, Nothing,Excel.XlSaveAsAccessMode.xlExclusive, Nothing, Nothing, Nothing, Nothing, Nothing);
//Excel的PrintOut方法,可以直接打印出来。
if (_isPrint)
{
ws.PrintOut(1, 1, 1, Nothing, Nothing, Nothing, Nothing, Nothing);
}
++rowcount;
}
ExcelDoc.Close(Nothing, Nothing, Nothing);
ExcelApp.Quit();
}
}
工程项目中实例化该Report类,按需要读写Excel。