C# 读写Excel

来源:互联网 发布:android xml布局优化 编辑:程序博客网 时间:2024/04/24 11:53

昨天公司一个部门要个小程序,要读写Excel,在网上搜了不少资料,结果程序做完了却在网上发现一个c#读写Excel的类,收藏了,呵呵

 

  1. //1.添加引用-〉com-〉microsoft excel 11.0 
  2. //2.若出现错误:命名空间“Microsoft.Office”中不存在类型或命名空间名称“Interop”(是缺少程序集引用吗?)
  3. //解决方法:先删除引用中的Excel,然后找到文件Microsoft.Office.Interop.Excel.dll,手动添加该文件的引用
  4. using System;
  5. using System.Data;
  6. using System.Reflection;
  7. using System.IO;
  8. using Microsoft.Office.Core;
  9. using System.Windows.Forms;
  10. using Excel = Microsoft.Office.Interop.Excel;
  11. namespace Wage.Common
  12. {
  13.     /// <summary>
  14.     /// 作者:李爱民
  15.     /// 功能描述:对Excel报表进行操作
  16.     /// 创建时间:2006-01-17, 修改时间:2007-1-14
  17.     /// 说明:在工程中需要添加 Excel11.0对象库的引用(Office 2000为Excel9.0,Office XP为Excel10.0);
  18.     ///       需要在Dcom中配置Excel应用程序的权限;
  19.     ///       服务器需要安装Office2003
  20.     /// </summary>
  21.     public class ExcelLib
  22.     {
  23.         //http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_wrcore/html/wrgrfexcelapplicationobject.asp
  24.         #region Variables
  25.         private Excel.Application excelApplication = null;
  26.         private Excel.Workbooks excelWorkBooks = null;
  27.         private Excel.Workbook excelWorkBook = null;
  28.         private Excel.Worksheet excelWorkSheet = null;
  29.         private Excel.Range excelRange = null;//Excel Range Object,多种用途
  30.         private Excel.Range excelCopySourceRange = null;//Excel Range Object
  31.         private int excelActiveWorkSheetIndex;          //活动工作表索引
  32.         private string excelOpenFileName = "";      //操作Excel的路径
  33.         private string excelSaveFileName = "";      //保存Excel的路径
  34.         #endregion
  35.         #region Properties
  36.         public int ActiveSheetIndex
  37.         {
  38.             get
  39.             {
  40.                 return excelActiveWorkSheetIndex;
  41.             }
  42.             set
  43.             {
  44.                 excelActiveWorkSheetIndex = value;
  45.             }
  46.         }
  47.         public string OpenFileName
  48.         {
  49.             get
  50.             {
  51.                 return excelOpenFileName;
  52.             }
  53.             set
  54.             {
  55.                 excelOpenFileName = value;
  56.             }
  57.         }
  58.         public string SaveFileName
  59.         {
  60.             get
  61.             {
  62.                 return excelSaveFileName;
  63.             }
  64.             set
  65.             {
  66.                 excelSaveFileName = value;
  67.             }
  68.         }
  69.         #endregion
  70.         //
  71.         //--------------------------------------------------------------------------------------------------------
  72.         /// <summary>
  73.         /// 构造函数;
  74.         /// </summary>
  75.         public ExcelLib()
  76.         {
  77.             excelApplication = null;//Excel Application Object
  78.             excelWorkBooks = null;//Workbooks
  79.             excelWorkBook = null;//Excel Workbook Object
  80.             excelWorkSheet = null;//Excel Worksheet Object
  81.             ActiveSheetIndex = 1;           //默认值活动工作簿为第一个;设置活动工作簿请参阅SetActiveWorkSheet()   
  82.         }
  83.         /// <summary>
  84.         /// 以excelOpenFileName为模板新建Excel文件
  85.         /// </summary>
  86.         public bool OpenExcelFile()
  87.         {
  88.             if (excelApplication != null) CloseExcelApplication();
  89.             //检查文件是否存在
  90.             if (excelOpenFileName == "")
  91.             {
  92.                 throw new Exception("请选择文件!");
  93.             }
  94.             if (!File.Exists(excelOpenFileName))
  95.             {
  96.                 throw new Exception(excelOpenFileName + "该文件不存在!");//该异常如何处理,由什么处理????
  97.             }
  98.             try
  99.             {
  100.                 excelApplication = new Excel.ApplicationClass();
  101.                 excelWorkBooks = excelApplication.Workbooks;
  102.                 excelWorkBook = ((Excel.Workbook)excelWorkBooks.Open(excelOpenFileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value));
  103.                 excelWorkSheet = (Excel.Worksheet)excelWorkBook.Worksheets[excelActiveWorkSheetIndex];
  104.                 excelApplication.Visible = false;
  105.                 return true;
  106.             }
  107.             catch (Exception e)
  108.             {
  109.                 CloseExcelApplication();
  110.                 MessageBox.Show("(1)没有安装Excel 2003;(2)或没有安装Excel 2003 .NET 可编程性支持;/n详细信息:"
  111.                     +e.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
  112.                 //throw new Exception(e.Message);
  113.                 return false;
  114.             }
  115.         }
  116.         /// <summary>
  117.         /// 读取一个Cell的值
  118.         /// </summary>
  119.         /// <param name="CellRowID">要读取的Cell的行索引</param>
  120.         /// <param name="CellColumnID">要读取的Cell的列索引</param>
  121.         /// <returns>Cell的值</returns>
  122.         public string getOneCellValue(int CellRowID, int CellColumnID)
  123.         {
  124.             if (CellRowID <= 0)
  125.             {
  126.                 throw new Exception("行索引超出范围!");
  127.             }
  128.             string sValue = "";
  129.             try
  130.             {
  131.                 sValue = ((Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID]).Text.ToString();
  132.             }
  133.             catch (Exception e)
  134.             {
  135.                 CloseExcelApplication();
  136.                 throw new Exception(e.Message);
  137.             }
  138.             return (sValue);
  139.         }
  140.         /// <summary>
  141.         /// 读取一个连续区域的Cell的值(矩形区域,包含一行或一列,或多行,多列),返回一个一维字符串数组。
  142.         /// </summary>
  143.         /// <param name="StartCell">StartCell是要写入区域的左上角单元格</param>
  144.         /// <param name="EndCell">EndCell是要写入区域的右下角单元格</param>
  145.         /// <returns>值的集合</returns>
  146.         public string[] getCellsValue(string StartCell, string EndCell)
  147.         {
  148.             string[] sValue = null;
  149.             //try
  150.             //{
  151.             excelRange = (Excel.Range)excelWorkSheet.get_Range(StartCell, EndCell);
  152.             sValue = new string[excelRange.Count];
  153.             int rowStartIndex = ((Excel.Range)excelWorkSheet.get_Range(StartCell, StartCell)).Row;      //起始行号
  154.             int columnStartIndex = ((Excel.Range)excelWorkSheet.get_Range(StartCell, StartCell)).Column;    //起始列号
  155.             int rowNum = excelRange.Rows.Count;                 //行数目
  156.             int columnNum = excelRange.Columns.Count;               //列数目
  157.             int index = 0;
  158.             for (int i = rowStartIndex; i < rowStartIndex + rowNum; i++)
  159.             {
  160.                 for (int j = columnStartIndex; j < columnNum + columnStartIndex; j++)
  161.                 {
  162.                     //读到空值null和读到空串""分别处理
  163.                     sValue[index] = ((Excel.Range)excelWorkSheet.Cells[i, j]).Text.ToString();
  164.                     index++;
  165.                 }
  166.             }
  167.             //}
  168.             //catch (Exception e)
  169.             //{
  170.             //    CloseExcelApplication();
  171.             //    throw new Exception(e.Message);
  172.             //}
  173.             return (sValue);
  174.         }
  175.         /// <summary>
  176.         /// 读取所有单元格的数据(矩形区域),返回一个datatable.假设所有单元格靠工作表左上区域。
  177.         /// </summary>
  178.         public DataTable getAllCellsValue()
  179.         {
  180.             int columnCount = getTotalColumnCount();
  181.             int rowCount = getTotalRowCount();
  182.             DataTable dt = new DataTable();
  183.             //设置datatable列的名称
  184.             for (int columnID = 1; columnID <= columnCount; columnID++)
  185.             {
  186.                 dt.Columns.Add(((Excel.Range)excelWorkSheet.Cells[1, columnID]).Text.ToString());
  187.             }
  188.             for (int rowID = 2; rowID <= rowCount; rowID++)
  189.             {
  190.                 DataRow dr = dt.NewRow();
  191.                 for (int columnID = 1; columnID <= columnCount; columnID++)
  192.                 {
  193.                     dr[columnID - 1] = ((Excel.Range)excelWorkSheet.Cells[rowID, columnID]).Text.ToString();
  194.                     //读到空值null和读到空串""分别处理
  195.                 }
  196.                 dt.Rows.Add(dr);
  197.             }
  198.             return (dt);
  199.         }
  200.         public int getTotalRowCount()
  201.         {//当前活动工作表中有效行数(总行数)
  202.             int rowsNumber = 0;
  203.             try
  204.             {
  205.                 while (true)
  206.                 {
  207.                     if (((Excel.Range)excelWorkSheet.Cells[rowsNumber + 1, 1]).Text.ToString().Trim() == "" &
  208.                            ((Excel.Range)excelWorkSheet.Cells[rowsNumber + 2, 1]).Text.ToString().Trim() == "" &
  209.                            ((Excel.Range)excelWorkSheet.Cells[rowsNumber + 3, 1]).Text.ToString().Trim() == "")
  210.                         break;
  211.                     rowsNumber++;
  212.                 }
  213.             }
  214.             catch
  215.             {
  216.                 return -1;
  217.             }
  218.             return rowsNumber;
  219.         }
  220.         /// <summary>
  221.         /// 当前活动工作表中有效列数(总列数)
  222.         /// </summary>
  223.         /// <param></param> 
  224.         public int getTotalColumnCount()
  225.         {
  226.             int columnNumber = 0;
  227.             try
  228.             {
  229.                 while (true)
  230.                 {
  231.                     if (((Excel.Range)excelWorkSheet.Cells[1, columnNumber + 1]).Text.ToString().Trim() == "" &
  232.                            ((Excel.Range)excelWorkSheet.Cells[1, columnNumber + 2]).Text.ToString().Trim() == "" &
  233.                            ((Excel.Range)excelWorkSheet.Cells[1, columnNumber + 3]).Text.ToString().Trim() == "")
  234.                         break;
  235.                     columnNumber++;
  236.                 }
  237.             }
  238.             catch
  239.             {
  240.                 return -1;
  241.             }
  242.             return columnNumber;
  243.         }
  244.         /// <summary>
  245.         /// 向一个Cell写入数据
  246.         /// </summary>
  247.         /// <param name="CellRowID">CellRowID是cell的行索引</param>
  248.         /// <param name="CellColumnID">CellColumnID是cell的列索引</param>
  249.         ///<param name="Value">要写入该单元格的数据值</param>
  250.         public void setOneCellValue(int CellRowID, int CellColumnID, string Value)
  251.         {
  252.             try
  253.             {
  254.                 excelRange = (Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID];
  255.                 excelRange.Value2 = Value;//Value2?
  256.                 //Gets or sets the value of the NamedRange control. 
  257.                 //The only difference between this property and the Value property is that Value2 is not a parameterized property. 
  258.                 excelRange = null;
  259.             }
  260.             catch (Exception e)
  261.             {
  262.                 CloseExcelApplication();
  263.                 throw new Exception(e.Message);
  264.             }
  265.         }
  266.         /// <summary>
  267.         /// 设置活动工作表
  268.         /// </summary>
  269.         /// <param name="SheetIndex">要设置为活动工作表的索引值</param>
  270.         public void SetActiveWorkSheet(int SheetIndex)
  271.         {
  272.             if (SheetIndex <= 0)
  273.             {
  274.                 throw new Exception("索引超出范围!");
  275.             }
  276.             try
  277.             {
  278.                 ActiveSheetIndex = SheetIndex;
  279.                 excelWorkSheet = (Excel.Worksheet)excelWorkBook.Worksheets[ActiveSheetIndex];
  280.             }
  281.             catch (Exception e)
  282.             {
  283.                 CloseExcelApplication();
  284.                 throw new Exception(e.Message);
  285.             }
  286.         }
  287.         /// <summary>
  288.         /// 向连续区域一次性写入数据;只有在区域连续和写入的值相同的情况下可以使用方法
  289.         /// </summary>
  290.         /// <param name="StartCell">StartCell是要写入区域的左上角单元格</param>
  291.         /// <param name="EndCell">EndCell是要写入区域的右下角单元格</param>
  292.         /// <param name="Value">要写入指定区域所有单元格的数据值</param>
  293.         public void setCellsValue(string StartCell, string EndCell, string Value)
  294.         {
  295.             try
  296.             {
  297.                 excelRange = excelWorkSheet.get_Range(StartCell, EndCell);
  298.                 excelRange.Value2 = Value;
  299.                 excelRange = null;
  300.             }
  301.             catch (Exception e)
  302.             {
  303.                 CloseExcelApplication();
  304.                 throw new Exception(e.Message);
  305.             }
  306.         }
  307.         /// <summary>
  308.         /// 给一行写数据
  309.         /// </summary>
  310.         public void setOneLineValues(int LineID, int StartCellColumnID, int EndCellColumnID, string[] Values)////已经测试
  311.         {
  312.             //用1-19号元素
  313.             //if (Values.Length!=EndCellColumnID-StartCellColumnID)
  314.             //{
  315.             //    throw new Exception("单元格数目与提供的值的数目不一致!");
  316.             //}
  317.             for (int i = StartCellColumnID; i <= EndCellColumnID; i++)
  318.             {
  319.                 setOneCellValue(LineID, i, Values[i]);
  320.             }
  321.         }
  322.         public void setCellsBorder(string startCell, string endCell)
  323.         {
  324.             //设置某个范围内的单元格的边框
  325.             excelRange = excelWorkSheet.get_Range(startCell, endCell);
  326.             excelRange.Borders[Excel.XlBordersIndex.xlEdgeLeft].LineStyle = Excel.XlLineStyle.xlContinuous;
  327.             excelRange.Borders[Excel.XlBordersIndex.xlEdgeTop].LineStyle = Excel.XlLineStyle.xlContinuous;
  328.             excelRange.Borders[Excel.XlBordersIndex.xlEdgeRight].LineStyle = Excel.XlLineStyle.xlContinuous;
  329.             excelRange.Borders[Excel.XlBordersIndex.xlEdgeBottom].LineStyle = Excel.XlLineStyle.xlContinuous;
  330.             excelRange.Borders[Excel.XlBordersIndex.xlInsideVertical].LineStyle = Excel.XlLineStyle.xlContinuous;
  331.             //excelRange.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle = Excel.XlLineStyle.xlContinuous;
  332.         }
  333.         public void setOneCellBorder(int CellRowID, int CellColumnID)
  334.         {
  335.             //设置某个单元格的边框
  336.             excelRange = (Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID];
  337.             excelRange.Borders[Excel.XlBordersIndex.xlEdgeLeft].LineStyle = Excel.XlLineStyle.xlContinuous;
  338.             excelRange.Borders[Excel.XlBordersIndex.xlEdgeTop].LineStyle = Excel.XlLineStyle.xlContinuous;
  339.             excelRange.Borders[Excel.XlBordersIndex.xlEdgeRight].LineStyle = Excel.XlLineStyle.xlContinuous;
  340.             excelRange.Borders[Excel.XlBordersIndex.xlEdgeBottom].LineStyle = Excel.XlLineStyle.xlContinuous;
  341.             //excelRange.Borders[Excel.XlBordersIndex.xlInsideVertical].LineStyle = Excel.XlLineStyle.xlContinuous;
  342.             //excelRange.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle = Excel.XlLineStyle.xlContinuous;
  343.         }
  344.         public void SetColumnWidth(string startCell, string endCell, int size)
  345.         {
  346.             //设置某个范围内的单元格的列的宽度
  347.             excelRange = excelWorkSheet.get_Range(startCell, endCell);
  348.             excelRange.ColumnWidth = size;
  349.         }
  350.         public void SetOneCellFont(int CellRowID, int CellColumnID, string fontName, int fontSize)
  351.         {
  352.             excelRange = (Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID];
  353.             excelRange.Font.Name = fontName;
  354.             excelRange.Font.Size = fontSize;
  355.         }
  356.         public void SetOneCellHorizontalAlignment(int CellRowID, int CellColumnID, Excel.Constants alignment)
  357.         {
  358.             excelRange = (Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID];
  359.             excelRange.HorizontalAlignment = alignment;
  360.         }
  361.         public void SetOneCellColumnWidth(int CellRowID, int CellColumnID, int size)
  362.         {
  363.             //设置某个单元格的列的宽度
  364.             excelRange = (Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID];
  365.             excelRange.ColumnWidth = size;
  366.         }
  367.         /// <summary>
  368.         /// 设置一个Cell的数据格式
  369.         /// </summary>
  370.         /// <param name="CellRowID">CellRowID是cell的行索引</param>
  371.         /// <param name="CellColumnID">CellColumnID是cell的列索引</param>
  372.         ///<param name="Value">数据格式</param>
  373.         public void setOneCellNumberFormat(int CellRowID, int CellColumnID, string numberFormat)
  374.         {
  375.             try
  376.             {
  377.                 excelRange = (Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID];
  378.                 excelRange.NumberFormatLocal = numberFormat;
  379.                 excelRange = null;
  380.             }
  381.             catch (Exception e)
  382.             {
  383.                 CloseExcelApplication();
  384.                 throw new Exception(e.Message);
  385.             }
  386.         }
  387.         public void SetRowHeight(string startCell, string endCell, int size)
  388.         {
  389.             //设置某个范围内的单元格的行的高度
  390.             excelRange = excelWorkSheet.get_Range(startCell, endCell);
  391.             excelRange.RowHeight = size;
  392.         }
  393.         public void SetRowHeight(int CellRowID, int CellColumnID, float size)
  394.         {
  395.             //设置某个范围内的单元格的行的高度
  396.             excelRange = (Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID];
  397.             excelRange.RowHeight = size;
  398.         }
  399.         public void SetOneCellRowHeight(int CellRowID, int CellColumnID, int size)
  400.         {
  401.             //设置某个单元格的行的高度
  402.             excelRange = (Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID];
  403.             excelRange.RowHeight = size;
  404.         }
  405.         /// <summary>
  406.         /// 拷贝区域.限制:在同一个工作表中复制
  407.         /// </summary>
  408.         /// <param name="SourceStart">源区域的左上角单元格</param>
  409.         /// <param name="SourceEnd">源区域的右下角单元格</param> 
  410.         /// <param name="DesStart">目标区域的左上角单元格</param> 
  411.         /// <param name="DesEnd">目标区域的右下角单元格</param> 
  412.         public void CopyCells(string SourceStart, string SourceEnd, string DesStart, string DesEnd)
  413.         {
  414.             try
  415.             {
  416.                 excelCopySourceRange = excelWorkSheet.get_Range(SourceStart, SourceEnd);
  417.                 excelRange = excelWorkSheet.get_Range(DesStart, DesEnd);
  418.                 excelCopySourceRange.Copy(excelRange);
  419.                 excelCopySourceRange = null;
  420.                 excelRange = null;
  421.             }
  422.             catch (Exception e)
  423.             {
  424.                 CloseExcelApplication();
  425.                 throw new Exception(e.Message);
  426.             }
  427.         }
  428.         public void CopyWorksheet(int SourceWorksheetIndex, int DesWorksheetIndex)
  429.         {
  430.             try
  431.             {
  432.                 //           Sheets("Sheet2").Select
  433.                 //Sheets("Sheet2").Copy After:=Sheets(3)
  434.                 Excel.Worksheet sheetSource = (Excel.Worksheet)excelWorkBook.Worksheets[SourceWorksheetIndex];
  435.                 sheetSource.Select(Missing.Value);
  436.                 Excel.Worksheet sheetDest = (Excel.Worksheet)excelWorkBook.Worksheets[DesWorksheetIndex];
  437.                 sheetSource.Copy(Missing.Value, sheetDest);
  438.             }
  439.             catch (Exception e)
  440.             {
  441.                 CloseExcelApplication();
  442.                 throw new Exception(e.Message);
  443.             }
  444.         }
  445.         /// <summary>
  446.         /// 插入一行
  447.         /// </summary>
  448.         /// <param name="CellRowID">要插入所在行的索引位置,插入后其原有行下移</param> 
  449.         /// <param name="RowNum">要插入行的个数</param> 
  450.         public void InsertRow(int CellRowID, int RowNum)//插入空行
  451.         {
  452.             if (CellRowID <= 0)
  453.             {
  454.                 throw new Exception("行索引超出范围!");
  455.             }
  456.             if (RowNum <= 0)
  457.             {
  458.                 throw new Exception("插入行数无效!");
  459.             }
  460.             try
  461.             {
  462.                 excelRange = (Excel.Range)excelWorkSheet.Rows[CellRowID, Missing.Value];
  463.                 for (int i = 0; i < RowNum; i++)
  464.                 {
  465.                     excelRange.Insert(Excel.XlDirection.xlDown, Missing.Value);
  466.                 }
  467.                 excelRange = null;
  468.             }
  469.             catch (Exception e)
  470.             {
  471.                 CloseExcelApplication();
  472.                 throw new Exception(e.Message);
  473.             }
  474.         }
  475.         /// <summary>
  476.         /// 保存Excel文件
  477.         /// </summary>
  478.         public Excel.Range FindFirstRange(Excel.Range xlRange, string FindText)//查找//没有测试
  479.         {
  480.             //查找第一个满足的区域
  481.             //Search for the first match
  482.             Excel.Range firstFind = null;
  483.             firstFind = xlRange.Find(FindText, Missing.Value, Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart, Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, false, Missing.Value, Missing.Value);
  484.             return firstFind;  //如果没找到,返回空
  485.         }
  486.         //http://msdn.microsoft.com/library/en-us/dv_wrcore/html/wrtskHowToSearchForTextInWorksheetRanges.asp?frame=true
  487.         /// <summary>
  488.         /// 当前活动工作表中有效行数(总行数)
  489.         /// </summary>
  490.         /// <param></param> 
  491.         /// <summary>
  492.         /// 判断单元格是否有数据
  493.         /// </summary>
  494.         public bool CellValueIsNull(int CellLineID, int CellColumnID)////已经测试
  495.         {
  496.             //判断单元格是否有数据
  497.             if ((((Excel.Range)excelWorkSheet.Cells[CellLineID, CellColumnID]).Text.ToString().Trim() != ""))
  498.                 return false;
  499.             return true;
  500.         }
  501.         public void newWorkbook(string excelTemplate, string fileName)
  502.         {
  503.             //以excelTemplate为模板新建文件fileName
  504.             //excelApplication.
  505.             excelWorkBook = excelWorkBooks.Add(excelTemplate);
  506.             SaveFileName = "";
  507.             SaveExcel();
  508.         }
  509.         public void newWorksheet()
  510.         {
  511.             excelWorkBook.Worksheets.Add(Missing.Value, Missing.Value, 1, Missing.Value);
  512.         }
  513.         public void setWorksheetName(int sheetIndex, string worksheetName)
  514.         {
  515.             // Missing.Value
  516.             Excel._Worksheet sheet = (Excel._Worksheet)(excelWorkBook.Worksheets[(object)sheetIndex]);
  517.             sheet.Name = worksheetName;
  518.         }
  519.         public void mergeOneLineCells(string startCell, string endCell)
  520.         {
  521.             //合并一行单元格 
  522.             excelRange = excelWorkSheet.get_Range(startCell, endCell);
  523.             //excelRange.Merge(true);
  524.             excelRange.MergeCells = true;
  525.         }
  526.         public void HorizontalAlignmentCells(string startCell, string endCell, Excel.Constants alignment)
  527.         {
  528.             //水平对齐一行单元格 
  529.             excelRange = excelWorkSheet.get_Range(startCell, endCell);
  530.             excelRange.HorizontalAlignment = alignment;
  531.         }
  532.         public void VerticalAlignmentCells(string startCell, string endCell, Excel.Constants alignment)
  533.         {
  534.             //垂直对齐一行单元格 
  535.             excelRange = excelWorkSheet.get_Range(startCell, endCell);
  536.             excelRange.VerticalAlignment = alignment;
  537.         }
  538.         //实现列号-〉字母 (26-〉Z,27->AA)
  539.         private string ConvertColumnIndexToChar(int columnIndex)
  540.         {
  541.             if (columnIndex < 1 || columnIndex > 256)
  542.             {
  543.                 MessageBox.Show("columnIndex=" + columnIndex + ",超出了有效范围(1-256)");
  544.                 return "A";
  545.             }
  546.             if (columnIndex >= 1 && columnIndex <= 26)//1--26
  547.             {
  548.                 return "AA";
  549.             }
  550.             if (columnIndex >= 27 && columnIndex <= 256)//27--256
  551.             {
  552.                 return "AA";
  553.             }
  554.             return "A";
  555.         }
  556.         //字母-〉列号 Z-〉26
  557.         public void SaveExcel()
  558.         {
  559.             if (excelSaveFileName == "")
  560.             {
  561.                 throw new Exception("未指定要保存的文件名");
  562.             }
  563.             try
  564.             {
  565.                 //excelWorkSheet.SaveAs(excelSaveFileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value);
  566.                 excelWorkSheet.SaveAs(excelSaveFileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value);
  567.             }
  568.             catch (Exception e)
  569.             {
  570.                 CloseExcelApplication();
  571.                 throw new Exception(e.Message);
  572.             }
  573.         }
  574.         //--------------------------------------------------------------------------------------------------------
  575.         /// <summary>
  576.         /// 保存Excel文件,格式xml.
  577.         /// </summary>
  578.         public void SaveExcelAsXML()
  579.         {
  580.             if (excelSaveFileName == "")
  581.             {
  582.                 throw new Exception("未指定要保存的文件名");
  583.             }
  584.             try
  585.             {
  586.                 //excelWorkSheet.SaveAs(excelSaveFileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value);
  587.                 excelWorkSheet.SaveAs(excelSaveFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlXMLSpreadsheet, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value);
  588.             }
  589.             catch (Exception e)
  590.             {
  591.                 CloseExcelApplication();
  592.                 throw new Exception(e.Message);
  593.             }
  594.         }
  595.         //--------------------------------------------------------------------------------------------------------
  596.         /// <summary>
  597.         /// 关闭Excel文件,释放对象;最后一定要调用此函数,否则会引起异常
  598.         /// </summary>
  599.         /// <param></param> 
  600.         public void CloseExcelApplication()
  601.         {
  602.             try
  603.             {
  604.                 excelWorkBooks = null;
  605.                 excelWorkBook = null;
  606.                 excelWorkSheet = null;
  607.                 excelRange = null;
  608.                 if (excelApplication != null)
  609.                 {
  610.                     excelApplication.Workbooks.Close();
  611.                     //Object missing = Type.Missing;
  612.                     excelApplication.Quit();
  613.                     excelApplication = null;
  614.                     //ReleaseAllRef(excelApplication);//Error
  615.                 }
  616.             }
  617.             finally
  618.             {
  619.                 GC.Collect();
  620.                 GC.WaitForPendingFinalizers();
  621.                 GC.Collect();
  622.                 GC.WaitForPendingFinalizers();
  623.             }
  624.         }
  625.         private void ReleaseAllRef(Object obj)
  626.         {//ReleaseComObject()方法可以使RCW减少一个对COM组件的引用,并返回减少一个引用后RCW对COM组件的剩余引用数量。
  627.             //我们用一个循环,就可以让RCW将所有对COM组件的引用全部去掉。
  628.             try
  629.             {
  630.                 while (System.Runtime.InteropServices.Marshal.ReleaseComObject(obj) > 1) ;
  631.             }
  632.             finally
  633.             {
  634.                 obj = null;
  635.             }
  636.         }
  637.     }
  638. }
原创粉丝点击