分享

C# 读写Excel 帮助类

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

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多