c#2005对excel的操作,只写了部分代码,以后会慢慢补充的。
/** Copyright(C) ryuusei Corporation 2009. All rights reserved.* 文件名 : TestOffice.cs* 系统名 : * 版本 : 0.0.0.0*/
using System;using System.Collections.Generic;using System.Text;using System.Data;using Excel=Microsoft.Office.Interop.Excel;using System.IO;class TestOffice{ /// <summary> /// excel主函数 /// </summary> /// <param name="strPath">excel的路径</param> /// <param name="dt">传入datatable</param> /// <returns>结果:成功 true;失败 false</returns> public bool ExcelMain(string strPath, DataTable dt) { //返回值 bool retFlag = false;
//判断datatable是否存在数据 if (dt.Rows.Count <= 0) { return retFlag; }
//判断文件是否存在 if (!File.Exists(strPath)) { return retFlag; }
//设置文件属性为normal File.SetAttributes(strPath,FileAttributes.Normal);
//建立Excel对象 Excel.Application oXls = new Excel.Application(); // 获得workbook对象 Excel.Workbook templateBook = GetExcelBook(oXls, templateDt); //获得worksheet对象 Excel.Worksheet workSheet = (Excel.Worksheet)workBook.Sheets.get_Item(1); //取消sheet保护 workSheet.Unprotect(Type.Missing); }
/// <summary> /// 获得workbook对象 /// </summary> /// <param name="oXls">excel对象</param> /// <param name="strPath">excel的路径</param> /// <returns>workbook对象</returns> private Excel.Workbook GetExcelBook(Excel.Application oXls, string strPath) { Excel.Workbooks oBooks = oXls.Workbooks; Excel.Workbook oBook = oBooks.Open(strPath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
return oBook; }
/// <summary> /// 拷贝模板worksheet /// </summary> /// <param name="templateBook">workbook对象</param> /// <param name="baseBook">模板workbook</param> /// <returns>结果:成功 true;失败 false</returns> private bool ExcelSheetAdd(Excel.Workbook templateBook, Excel.Workbook baseBook) { Excel.Worksheet sheet = (Excel.Worksheet)baseBook.Worksheets[1]; Excel.Worksheet to = (Excel.Worksheet)templateBook.Worksheets[1]; sheet.Copy(to, Type.Missing);
return true; }}