using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; using Excel = Microsoft.Office.Interop.Excel; using System.Diagnostics; using System.IO; using System.Collections; using System.Data; namespace Core.Helper { /// <summary> /// excel操作類 /// 開發環境:2007 /// </summary> public class ExcelHelper : IDisposable { #region 構造函數 /// <summary> /// 構造函數,將一個已有Excel工作簿作為模板,並指定輸出路徑 /// </summary> /// <param name="templetFilePath">Excel模板文件路徑</param> /// <param name="outputFilePath">輸出Excel文件路徑</param> public ExcelHelper(string templetFilePath, string outputFilePath) { if (templetFilePath == null) throw new Exception("Excel模板文件路徑不能為空!"); if (outputFilePath == null) throw new Exception("輸出Excel文件路徑不能為空!"); if (!File.Exists(templetFilePath)) throw new Exception("指定路徑的Excel模板文件不存在!"); this.templetFile = templetFilePath; this.outputFile = outputFilePath; excelApp = new Excel.ApplicationClass(); excelApp.Visible = false; excelApp.DisplayAlerts = false; excelApp.AlertBeforeOverwriting = false; //打開模板文件,得到WorkBook對象 workBook = excelApp.Workbooks.Open(templetFile, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, Type.Missing, Type.Missing); //得到WorkSheet對象 workSheet = (Excel.Worksheet)workBook.Sheets.get_Item(1); } DateTime beforeTime; DateTime afterTime; /// <summary> /// 構造函數,打開一個已有的工作簿 /// </summary> /// <param name="fileName">Excel文件名</param> public ExcelHelper(string fileName) { if (!File.Exists(fileName)) throw new Exception("指定路徑的Excel文件不存在!"); //創建一個Application對象並使其可見 beforeTime = DateTime.Now; excelApp = new Excel.ApplicationClass(); excelApp.Visible = false; excelApp.DisplayAlerts = false; excelApp.AlertBeforeOverwriting = false; //打開一個WorkBook workBook = excelApp.Workbooks.Open(fileName, 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); afterTime = DateTime.Now; //得到WorkSheet對象 workSheet = (Excel.Worksheet)workBook.Sheets.get_Item(1); } /// <summary> /// 構造函數,新建一個工作簿 /// </summary> public ExcelHelper() { beforeTime = DateTime.Now; excelApp = new Excel.ApplicationClass(); afterTime = DateTime.Now; excelApp.Visible = false; //設置禁止彈出保存和覆蓋的詢問提示框 excelApp.DisplayAlerts = false; excelApp.AlertBeforeOverwriting = false; //新建一個WorkBook workBook = excelApp.Workbooks.Add(Type.Missing); //得到WorkSheet對象 workSheet = (Excel.Worksheet)workBook.Sheets.get_Item(1); } #endregion #region 成員變量 private string templetFile = null; private string outputFile = null; private object missing = System.Reflection.Missing.Value; Excel.Application excelApp; Excel.Workbook workBook; Excel.Worksheet workSheet; Excel.Range range; Excel.Range range1; Excel.Range range2; Excel.TextBox textBox; private int sheetCount = 1; //WorkSheet數量 private string sheetPrefixName = "頁"; #endregion #region 公共屬性 /// <summary> /// WorkSheet前綴名,比如:前綴名為“頁”,那么WorkSheet名稱依次為“頁-1,頁-2...” /// </summary> public string SheetPrefixName { set { this.sheetPrefixName = value; } } /// <summary> /// WorkSheet數量 /// </summary> public int WorkSheetCount { get { return workBook.Sheets.Count; } } /// <summary> /// Excel模板文件路徑 /// </summary> public string TempletFilePath { set { this.templetFile = value; } } /// <summary> /// 輸出Excel文件路徑 /// </summary> public string OutputFilePath { set { this.outputFile = value; } } #endregion #region 公共方法 #region Data Export Methods /// <summary> /// 將DataTable數據寫入Excel文件(自動分頁) /// </summary> /// <param name="dt">DataTable</param> /// <param name="rows">每個WorkSheet寫入多少行數據</param> /// <param name="top">表格數據起始行索引</param> /// <param name="left">表格數據起始列索引</param> public void DataTableToExcel(DataTable dt, int rows, int top, int left) { int rowCount = dt.Rows.Count; //DataTable行數 int colCount = dt.Columns.Count; //DataTable列數 sheetCount = this.GetSheetCount(rowCount, rows); //WorkSheet個數 // StringBuilder sb; //復制sheetCount-1個WorkSheet對象 for (int i = 1; i < sheetCount; i++) { workSheet = (Excel.Worksheet)workBook.Worksheets.get_Item(i); workSheet.Copy(missing, workBook.Worksheets[i]); } for (int i = 1; i <= sheetCount; i++) { int startRow = (i - 1) * rows; //記錄起始行索引 int endRow = i * rows; //記錄結束行索引 //若是最后一個WorkSheet,那么記錄結束行索引為源DataTable行數 if (i == sheetCount) endRow = rowCount; //獲取要寫入數據的WorkSheet對象,並重命名 workSheet = (Excel.Worksheet)workBook.Worksheets.get_Item(i); workSheet.Name = sheetPrefixName + "-" + i.ToString(); //將dt中的數據寫入WorkSheet // for(int j=0;j<endRow-startRow;j++) // { // for(int k=0;k<colCount;k++) // { // workSheet.Cells[top + j,left + k] = dt.Rows[startRow + j][k].ToString(); // } // } //利用二維數組批量寫入 int row = endRow - startRow; object[,] ss = new object[row, colCount]; for (int j = 0; j < row; j++) { for (int k = 0; k < colCount; k++) { ss[j, k] = dt.Rows[startRow + j][k].ToString(); } } range = (Excel.Range)workSheet.Cells[top, left]; range = range.get_Resize(row, colCount); range.Value2 = ss; #region 利用Windwo粘貼板批量拷貝數據(在Web下面行不通) /*sb = new StringBuilder(); for(int j=0;j<endRow-startRow;j++) { for(int k=0;k<colCount;k++) { sb.Append( dt.Rows[startRow + j][k].ToString() ); sb.Append("\t"); } sb.Append("\n"); } System.Windows.Forms.Clipboard.SetDataObject(sb.ToString()); range = (Excel.Range)workSheet.Cells[top,left]; workSheet.Paste(range,false);*/ #endregion } } /// <summary> /// 將DataTable數據寫入Excel文件(不分頁) /// </summary> /// <param name="dt">DataTable</param> /// <param name="top">表格數據起始行索引</param> /// <param name="left">表格數據起始列索引</param> public void DataTableToExcel(DataTable dt, int top, int left) { int rowCount = dt.Rows.Count; //DataTable行數 int colCount = dt.Columns.Count; //DataTable列數 //利用二維數組批量寫入 object[,] arr = new object[rowCount, colCount]; for (int j = 0; j < rowCount; j++) { for (int k = 0; k < colCount; k++) { arr[j, k] = dt.Rows[j][k].ToString(); } } range = (Excel.Range)workSheet.Cells[top, left]; range = range.get_Resize(rowCount, colCount); range.Value2 = arr; } public void DataTableToExcel(DataTable dt, int top, int left, Excel.Worksheet objSheet) { int rowCount = dt.Rows.Count; //DataTable行數 int colCount = dt.Columns.Count; //DataTable列數 //利用二維數組批量寫入 object[,] arr = new object[rowCount, colCount]; for (int j = 0; j < rowCount; j++) { for (int k = 0; k < colCount; k++) { arr[j, k] = dt.Rows[j][k].ToString(); } } range = (Excel.Range)objSheet.Cells[top, left]; range = range.get_Resize(rowCount, colCount); range.Value2 = arr; } /// <summary> /// 將DataTable數據寫入Excel文件(自動分頁,並指定要合並的列索引) /// </summary> /// <param name="dt">DataTable</param> /// <param name="rows">每個WorkSheet寫入多少行數據</param> /// <param name="top">表格數據起始行索引</param> /// <param name="left">表格數據起始列索引</param> /// <param name="mergeColumnIndex">DataTable中要合並相同行的列索引,從0開始</param> public void DataTableToExcel(DataTable dt, int rows, int top, int left, int mergeColumnIndex) { int rowCount = dt.Rows.Count; //源DataTable行數 int colCount = dt.Columns.Count; //源DataTable列數 sheetCount = this.GetSheetCount(rowCount, rows); //WorkSheet個數 // StringBuilder sb; //復制sheetCount-1個WorkSheet對象 for (int i = 1; i < sheetCount; i++) { workSheet = (Excel.Worksheet)workBook.Worksheets.get_Item(i); workSheet.Copy(missing, workBook.Worksheets[i]); } for (int i = 1; i <= sheetCount; i++) { int startRow = (i - 1) * rows; //記錄起始行索引 int endRow = i * rows; //記錄結束行索引 //若是最后一個WorkSheet,那么記錄結束行索引為源DataTable行數 if (i == sheetCount) endRow = rowCount; //獲取要寫入數據的WorkSheet對象,並重命名 workSheet = (Excel.Worksheet)workBook.Worksheets.get_Item(i); workSheet.Name = sheetPrefixName + "-" + i.ToString(); //將dt中的數據寫入WorkSheet // for(int j=0;j<endRow-startRow;j++) // { // for(int k=0;k<colCount;k++) // { // workSheet.Cells[top + j,left + k] = dt.Rows[startRow + j][k].ToString(); // } // } //利用二維數組批量寫入 int row = endRow - startRow; object[,] ss = new object[row, colCount]; for (int j = 0; j < row; j++) { for (int k = 0; k < colCount; k++) { ss[j, k] = dt.Rows[startRow + j][k].ToString(); } } range = (Excel.Range)workSheet.Cells[top, left]; range = range.get_Resize(row, colCount); range.Value2 = ss; //合並相同行 this.MergeRows(workSheet, left + mergeColumnIndex, top, rows); } } /// <summary> /// 將二維數組數據寫入Excel文件(自動分頁) /// </summary> /// <param name="arr">二維數組</param> /// <param name="rows">每個WorkSheet寫入多少行數據</param> /// <param name="top">行索引</param> /// <param name="left">列索引</param> public void ArrayToExcel(object[,] arr, int rows, int top, int left) { int rowCount = arr.GetLength(0); //二維數組行數(一維長度) int colCount = arr.GetLength(1); //二維數據列數(二維長度) sheetCount = this.GetSheetCount(rowCount, rows); //WorkSheet個數 //復制sheetCount-1個WorkSheet對象 for (int i = 1; i < sheetCount; i++) { workSheet = (Excel.Worksheet)workBook.Worksheets.get_Item(i); workSheet.Copy(missing, workBook.Worksheets[i]); } //將二維數組數據寫入Excel for (int i = sheetCount; i >= 1; i--) { int startRow = (i - 1) * rows; //記錄起始行索引 int endRow = i * rows; //記錄結束行索引 //若是最后一個WorkSheet,那么記錄結束行索引為源DataTable行數 if (i == sheetCount) endRow = rowCount; //獲取要寫入數據的WorkSheet對象,並重命名 workSheet = (Excel.Worksheet)workBook.Worksheets.get_Item(i); workSheet.Name = sheetPrefixName + "-" + i.ToString(); //將二維數組中的數據寫入WorkSheet // for(int j=0;j<endRow-startRow;j++) // { // for(int k=0;k<colCount;k++) // { // workSheet.Cells[top + j,left + k] = arr[startRow + j,k]; // } // } //利用二維數組批量寫入 int row = endRow - startRow; object[,] ss = new object[row, colCount]; for (int j = 0; j < row; j++) { for (int k = 0; k < colCount; k++) { ss[j, k] = arr[startRow + j, k]; } } range = (Excel.Range)workSheet.Cells[top, left]; range = range.get_Resize(row, colCount); range.Value2 = ss; } }//end ArrayToExcel /// <summary> /// 將二維數組數據寫入Excel文件(不分頁) /// </summary> /// <param name="arr">二維數組</param> /// <param name="top">行索引</param> /// <param name="left">列索引</param> public void ArrayToExcel(object[,] arr, int top, int left) { int rowCount = arr.GetLength(0); //二維數組行數(一維長度) int colCount = arr.GetLength(1); //二維數據列數(二維長度) range = (Excel.Range)workSheet.Cells[top, left]; range = range.get_Resize(rowCount, colCount); range.FormulaArray = arr; }//end ArrayToExcel /// <summary> /// 將二維數組數據寫入Excel文件(不分頁) /// </summary> /// <param name="arr">二維數組</param> /// <param name="top">行索引</param> /// <param name="left">列索引</param> /// <param name="isFormula">填充的數據是否需要計算</param> public void ArrayToExcel(object[,] arr, int top, int left, bool isFormula) { int rowCount = arr.GetLength(0); //二維數組行數(一維長度) int colCount = arr.GetLength(1); //二維數據列數(二維長度) range = (Excel.Range)workSheet.Cells[top, left]; range = range.get_Resize(rowCount, colCount); //注意:使用range.FormulaArray寫合並的單元格會出問題 if (isFormula) range.FormulaArray = arr; else range.Value2 = arr; }//end ArrayToExcel /// <summary> /// 將二維數組數據寫入Excel文件(不分頁),合並指定列的相同行 /// </summary> /// <param name="arr">二維數組</param> /// <param name="top">行索引</param> /// <param name="left">列索引</param> /// <param name="isFormula">填充的數據是否需要計算</param> /// <param name="mergeColumnIndex">需要合並行的列索引</param> public void ArrayToExcel(object[,] arr, int top, int left, bool isFormula, int mergeColumnIndex) { int rowCount = arr.GetLength(0); //二維數組行數(一維長度) int colCount = arr.GetLength(1); //二維數據列數(二維長度) range = (Excel.Range)workSheet.Cells[top, left]; range = range.get_Resize(rowCount, colCount); //注意:使用range.FormulaArray寫合並的單元格會出問題 if (isFormula) range.FormulaArray = arr; else range.Value2 = arr; this.MergeRows(workSheet, mergeColumnIndex, top, rowCount); }//end ArrayToExcel /// <summary> /// 將二維數組數據寫入Excel文件(不分頁) /// </summary> /// <param name="sheetIndex">工作表索引</param> /// <param name="arr">二維數組</param> /// <param name="top">行索引</param> /// <param name="left">列索引</param> public void ArrayToExcel(int sheetIndex, object[,] arr, int top, int left) { if (sheetIndex > this.WorkSheetCount) { this.KillExcelProcess(false); throw new Exception("索引超出范圍,WorkSheet索引不能大於WorkSheet數量!"); } // 改變當前工作表 this.workSheet = (Excel.Worksheet)this.workBook.Sheets.get_Item(sheetIndex); int rowCount = arr.GetLength(0); //二維數組行數(一維長度) int colCount = arr.GetLength(1); //二維數據列數(二維長度) range = (Excel.Range)workSheet.Cells[top, left]; range = range.get_Resize(rowCount, colCount); range.Value2 = arr; }//end ArrayToExcel /// <summary> /// 將二維數組數據寫入Excel文件(自動分頁,並指定要合並的列索引) /// </summary> /// <param name="arr">二維數組</param> /// <param name="rows">每個WorkSheet寫入多少行數據</param> /// <param name="top">行索引</param> /// <param name="left">列索引</param> /// <param name="mergeColumnIndex">數組的二維索引,相當於DataTable的列索引,索引從0開始</param> public void ArrayToExcel(object[,] arr, int rows, int top, int left, int mergeColumnIndex) { int rowCount = arr.GetLength(0); //二維數組行數(一維長度) int colCount = arr.GetLength(1); //二維數據列數(二維長度) sheetCount = this.GetSheetCount(rowCount, rows); //WorkSheet個數 //復制sheetCount-1個WorkSheet對象 for (int i = 1; i < sheetCount; i++) { workSheet = (Excel.Worksheet)workBook.Worksheets.get_Item(i); workSheet.Copy(missing, workBook.Worksheets[i]); } //將二維數組數據寫入Excel for (int i = sheetCount; i >= 1; i--) { int startRow = (i - 1) * rows; //記錄起始行索引 int endRow = i * rows; //記錄結束行索引 //若是最后一個WorkSheet,那么記錄結束行索引為源DataTable行數 if (i == sheetCount) endRow = rowCount; //獲取要寫入數據的WorkSheet對象,並重命名 workSheet = (Excel.Worksheet)workBook.Worksheets.get_Item(i); workSheet.Name = sheetPrefixName + "-" + i.ToString(); //將二維數組中的數據寫入WorkSheet for (int j = 0; j < endRow - startRow; j++) { for (int k = 0; k < colCount; k++) { workSheet.Cells[top + j, left + k] = arr[startRow + j, k]; } } //利用二維數組批量寫入 int row = endRow - startRow; object[,] ss = new object[row, colCount]; for (int j = 0; j < row; j++) { for (int k = 0; k < colCount; k++) { ss[j, k] = arr[startRow + j, k]; } } range = (Excel.Range)workSheet.Cells[top, left]; range = range.get_Resize(row, colCount); range.Value2 = ss; //合並相同行 this.MergeRows(workSheet, left + mergeColumnIndex, top, rows); } }//end ArrayToExcel #endregion #region WorkSheet Methods /// <summary> /// 改變當前工作表 /// </summary> /// <param name="sheetIndex">工作表索引</param> public void ChangeCurrentWorkSheet(int sheetIndex) { //若指定工作表索引超出范圍,則不改變當前工作表 if (sheetIndex < 1) return; if (sheetIndex > this.WorkSheetCount) return; this.workSheet = (Excel.Worksheet)this.workBook.Sheets.get_Item(sheetIndex); } /// <summary> /// 隱藏指定名稱的工作表 /// </summary> /// <param name="sheetName">工作表名稱</param> public void HiddenWorkSheet(string sheetName) { try { Excel.Worksheet sheet = null; for (int i = 1; i <= this.WorkSheetCount; i++) { workSheet = (Excel.Worksheet)workBook.Sheets.get_Item(i); if (workSheet.Name == sheetName) sheet = workSheet; } if (sheet != null) sheet.Visible = Excel.XlSheetVisibility.xlSheetHidden; else { this.KillExcelProcess(false); throw new Exception("名稱為\"" + sheetName + "\"的工作表不存在"); } } catch (Exception e) { this.KillExcelProcess(false); throw e; } } /// <summary> /// 隱藏指定索引的工作表 /// </summary> /// <param name="sheetIndex"></param> public void HiddenWorkSheet(int sheetIndex) { if (sheetIndex > this.WorkSheetCount) { this.KillExcelProcess(false); throw new Exception("索引超出范圍,WorkSheet索引不能大於WorkSheet數量!"); } try { Excel.Worksheet sheet = null; sheet = (Excel.Worksheet)workBook.Sheets.get_Item(sheetIndex); sheet.Visible = Excel.XlSheetVisibility.xlSheetHidden; } catch (Exception e) { this.KillExcelProcess(false); throw e; } } /// <summary> /// 在指定名稱的工作表后面拷貝指定個數的該工作表的副本,並重命名 /// </summary> /// <param name="sheetName">工作表名稱</param> /// <param name="sheetCount">工作表個數</param> public void CopyWorkSheets(string sheetName, int sheetCount) { try { Excel.Worksheet sheet = null; int sheetIndex = 0; for (int i = 1; i <= this.WorkSheetCount; i++) { workSheet = (Excel.Worksheet)workBook.Sheets.get_Item(i); if (workSheet.Name == sheetName) { sheet = workSheet; sheetIndex = workSheet.Index; } } if (sheet != null) { for (int i = sheetCount; i >= 1; i--) { sheet.Copy(this.missing, sheet); } //重命名 for (int i = sheetIndex; i <= sheetIndex + sheetCount; i++) { workSheet = (Excel.Worksheet)workBook.Sheets.get_Item(i); workSheet.Name = sheetName + "-" + Convert.ToString(i - sheetIndex + 1); } } else { this.KillExcelProcess(false); throw new Exception("名稱為\"" + sheetName + "\"的工作表不存在"); } } catch (Exception e) { this.KillExcelProcess(false); throw e; } } /// <summary> /// 將一個工作表拷貝到另一個工作表后面,並重命名 /// </summary> /// <param name="srcSheetIndex">拷貝源工作表索引</param> /// <param name="aimSheetIndex">參照位置工作表索引,新工作表拷貝在該工作表后面</param> /// <param name="newSheetName"></param> public void CopyWorkSheet(int srcSheetIndex, int aimSheetIndex, string newSheetName) { if (srcSheetIndex > this.WorkSheetCount || aimSheetIndex > this.WorkSheetCount) { this.KillExcelProcess(false); throw new Exception("索引超出范圍,WorkSheet索引不能大於WorkSheet數量!"); } try { Excel.Worksheet srcSheet = (Excel.Worksheet)workBook.Sheets.get_Item(srcSheetIndex); Excel.Worksheet aimSheet = (Excel.Worksheet)workBook.Sheets.get_Item(aimSheetIndex); srcSheet.Copy(this.missing, aimSheet); //重命名 workSheet = (Excel.Worksheet)aimSheet.Next; //獲取新拷貝的工作表 workSheet.Name = newSheetName; } catch (Exception e) { this.KillExcelProcess(false); throw e; } } /// <summary> /// 根據名稱刪除工作表 /// </summary> /// <param name="sheetName"></param> public void DeleteWorkSheet(string sheetName) { try { Excel.Worksheet sheet = null; //找到名稱位sheetName的工作表 for (int i = 1; i <= this.WorkSheetCount; i++) { workSheet = (Excel.Worksheet)workBook.Sheets.get_Item(i); if (workSheet.Name == sheetName) { sheet = workSheet; } } if (sheet != null) { sheet.Delete(); } else { this.KillExcelProcess(false); throw new Exception("名稱為\"" + sheetName + "\"的工作表不存在"); } } catch (Exception e) { this.KillExcelProcess(false); throw e; } } /// <summary> /// 根據索引刪除工作表 /// </summary> /// <param name="sheetIndex"></param> public void DeleteWorkSheet(int sheetIndex) { if (sheetIndex > this.WorkSheetCount) { this.KillExcelProcess(false); throw new Exception("索引超出范圍,WorkSheet索引不能大於WorkSheet數量!"); } try { Excel.Worksheet sheet = null; sheet = (Excel.Worksheet)workBook.Sheets.get_Item(sheetIndex); sheet.Delete(); } catch (Exception e) { this.KillExcelProcess(false); throw e; } } #endregion #region TextBox Methods /// <summary> /// 向指定文本框寫入數據,對每個WorkSheet操作 /// </summary> /// <param name="textboxName">文本框名稱</param> /// <param name="text">要寫入的文本</param> public void SetTextBox(string textboxName, string text) { for (int i = 1; i <= this.WorkSheetCount; i++) { workSheet = (Excel.Worksheet)workBook.Worksheets.get_Item(i); try { textBox = (Excel.TextBox)workSheet.TextBoxes(textboxName); textBox.Text = text; } catch { this.KillExcelProcess(false); throw new Exception("不存在ID為\"" + textboxName + "\"的文本框!"); } } } /// <summary> /// 向指定文本框寫入數據,對指定WorkSheet操作 /// </summary> /// <param name="sheetIndex">工作表索引</param> /// <param name="textboxName">文本框名稱</param> /// <param name="text">要寫入的文本</param> public void SetTextBox(int sheetIndex, string textboxName, string text) { workSheet = (Excel.Worksheet)workBook.Worksheets.get_Item(sheetIndex); try { textBox = (Excel.TextBox)workSheet.TextBoxes(textboxName); textBox.Text = text; } catch { this.KillExcelProcess(false); throw new Exception("不存在ID為\"" + textboxName + "\"的文本框!"); } } /// <summary> /// 向文本框寫入數據,對每個WorkSheet操作 /// </summary> /// <param name="ht">Hashtable的鍵值對保存文本框的ID和數據</param> public void SetTextBoxes(Hashtable ht) { if (ht.Count == 0) return; for (int i = 1; i <= this.WorkSheetCount; i++) { workSheet = (Excel.Worksheet)workBook.Worksheets.get_Item(i); foreach (DictionaryEntry dic in ht) { try { textBox = (Excel.TextBox)workSheet.TextBoxes(dic.Key); textBox.Text = dic.Value.ToString(); } catch { this.KillExcelProcess(false); throw new Exception("不存在ID為\"" + dic.Key.ToString() + "\"的文本框!"); } } } } /// <summary> /// 向文本框寫入數據,對指定WorkSheet操作 /// </summary> /// <param name="ht">Hashtable的鍵值對保存文本框的ID和數據</param> public void SetTextBoxes(int sheetIndex, Hashtable ht) { if (ht.Count == 0) return; if (sheetIndex > this.WorkSheetCount) { this.KillExcelProcess(false); throw new Exception("索引超出范圍,WorkSheet索引不能大於WorkSheet數量!"); } workSheet = (Excel.Worksheet)workBook.Worksheets.get_Item(sheetIndex); foreach (DictionaryEntry dic in ht) { try { textBox = (Excel.TextBox)workSheet.TextBoxes(dic.Key); textBox.Text = dic.Value.ToString(); } catch { this.KillExcelProcess(false); throw new Exception("不存在ID為\"" + dic.Key.ToString() + "\"的文本框!"); } } } #endregion #region Cell Methods /// <summary> /// 向單元格寫入數據,對當前WorkSheet操作 /// </summary> /// <param name="rowIndex">行索引</param> /// <param name="columnIndex">列索引</param> /// <param name="text">要寫入的文本值</param> public void SetCells(int rowIndex, int columnIndex, string text) { try { workSheet.Cells[rowIndex, columnIndex] = text; } catch { this.KillExcelProcess(false); throw new Exception("向單元格[" + rowIndex + "," + columnIndex + "]寫數據出錯!"); } } /// <summary> /// 向單元格寫入數據,對指定WorkSheet操作 /// </summary> /// <param name="sheetIndex">工作表索引</param> /// <param name="rowIndex">行索引</param> /// <param name="columnIndex">列索引</param> /// <param name="text">要寫入的文本值</param> public void SetCells(int sheetIndex, int rowIndex, int columnIndex, string text) { try { this.ChangeCurrentWorkSheet(sheetIndex); //改變當前工作表為指定工作表 workSheet.Cells[rowIndex, columnIndex] = text; } catch { this.KillExcelProcess(false); throw new Exception("向單元格[" + rowIndex + "," + columnIndex + "]寫數據出錯!"); } } /// <summary> /// 向單元格寫入數據,對每個WorkSheet操作 /// </summary> /// <param name="ht">Hashtable的鍵值對保存單元格的位置索引(行索引和列索引用“,”隔開)和數據</param> public void SetCells(Hashtable ht) { int rowIndex; int columnIndex; string position; if (ht.Count == 0) return; for (int i = 1; i <= this.WorkSheetCount; i++) { workSheet = (Excel.Worksheet)workBook.Worksheets.get_Item(i); foreach (DictionaryEntry dic in ht) { try { position = dic.Key.ToString(); rowIndex = Convert.ToInt32(position.Split(',')[0]); columnIndex = Convert.ToInt32(position.Split(',')[1]); workSheet.Cells[rowIndex, columnIndex] = dic.Value; } catch { this.KillExcelProcess(false); throw new Exception("向單元格[" + dic.Key + "]寫數據出錯!"); } } } } /// <summary> /// 向單元格寫入數據,對指定WorkSheet操作 /// </summary> /// <param name="ht">Hashtable的鍵值對保存單元格的位置索引(行索引和列索引用“,”隔開)和數據</param> public void SetCells(int sheetIndex, Hashtable ht) { int rowIndex; int columnIndex; string position; if (sheetIndex > this.WorkSheetCount) { this.KillExcelProcess(false); throw new Exception("索引超出范圍,WorkSheet索引不能大於WorkSheet數量!"); } if (ht.Count == 0) return; workSheet = (Excel.Worksheet)workBook.Worksheets.get_Item(sheetIndex); foreach (DictionaryEntry dic in ht) { try { position = dic.Key.ToString(); rowIndex = Convert.ToInt32(position.Split(',')[0]); columnIndex = Convert.ToInt32(position.Split(',')[1]); workSheet.Cells[rowIndex, columnIndex] = dic.Value; } catch { this.KillExcelProcess(false); throw new Exception("向單元格[" + dic.Key + "]寫數據出錯!"); } } } /// <summary> /// 設置單元格為可計算的 /// </summary> /// <remarks> /// 如果Excel的單元格格式設置為數字,日期或者其他類型時,需要設置這些單元格的FormulaR1C1屬性, /// 否則寫到這些單元格的數據將不會按照預先設定的格式顯示 /// </remarks> /// <param name="arr">保存單元格的位置索引(行索引和列索引用“,”隔開)和數據</param> public void SetCells(int sheetIndex, string[] arr) { int rowIndex; int columnIndex; string position; if (sheetIndex > this.WorkSheetCount) { this.KillExcelProcess(false); throw new Exception("索引超出范圍,WorkSheet索引不能大於WorkSheet數量!"); } if (arr.Length == 0) return; workSheet = (Excel.Worksheet)workBook.Worksheets.get_Item(sheetIndex); for (int i = 0; i < arr.Length; i++) { try { position = arr[i]; rowIndex = Convert.ToInt32(position.Split(',')[0]); columnIndex = Convert.ToInt32(position.Split(',')[1]); Excel.Range cell = (Excel.Range)workSheet.Cells[rowIndex, columnIndex]; cell.FormulaR1C1 = cell.Text; } catch { this.KillExcelProcess(false); throw new Exception(string.Format("計算單元格{0}出錯!", arr[i])); } } } /// <summary> /// 向單元格寫入數據,對指定WorkSheet操作 /// </summary> /// <param name="ht">Hashtable的鍵值對保存單元格的位置索引(行索引和列索引用“,”隔開)和數據</param> public void SetCells(string sheetName, Hashtable ht) { int rowIndex; int columnIndex; string position; Excel.Worksheet sheet = null; int sheetIndex = 0; if (ht.Count == 0) return; try { for (int i = 1; i <= this.WorkSheetCount; i++) { workSheet = (Excel.Worksheet)workBook.Sheets.get_Item(i); if (workSheet.Name == sheetName) { sheet = workSheet; sheetIndex = workSheet.Index; } } if (sheet != null) { foreach (DictionaryEntry dic in ht) { try { position = dic.Key.ToString(); rowIndex = Convert.ToInt32(position.Split(',')[0]); columnIndex = Convert.ToInt32(position.Split(',')[1]); sheet.Cells[rowIndex, columnIndex] = dic.Value; } catch { this.KillExcelProcess(false); throw new Exception("向單元格[" + dic.Key + "]寫數據出錯!"); } } } else { this.KillExcelProcess(false); throw new Exception("名稱為\"" + sheetName + "\"的工作表不存在"); } } catch (Exception e) { this.KillExcelProcess(false); throw e; } } /// <summary> /// 合並單元格,並賦值,對每個WorkSheet操作 /// </summary> /// <param name="beginRowIndex">開始行索引</param> /// <param name="beginColumnIndex">開始列索引</param> /// <param name="endRowIndex">結束行索引</param> /// <param name="endColumnIndex">結束列索引</param> /// <param name="text">合並后Range的值</param> public void MergeCells(int beginRowIndex, int beginColumnIndex, int endRowIndex, int endColumnIndex, string text) { for (int i = 1; i <= this.WorkSheetCount; i++) { workSheet = (Excel.Worksheet)workBook.Worksheets.get_Item(i); range = workSheet.get_Range(workSheet.Cells[beginRowIndex, beginColumnIndex], workSheet.Cells[endRowIndex, endColumnIndex]); range.ClearContents(); //先把Range內容清除,合並才不會出錯 range.MergeCells = true; range.Value2 = text; range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; range.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter; } } /// <summary> /// 合並單元格,並賦值,對指定WorkSheet操作 /// </summary> /// <param name="sheetIndex">WorkSheet索引</param> /// <param name="beginRowIndex">開始行索引</param> /// <param name="beginColumnIndex">開始列索引</param> /// <param name="endRowIndex">結束行索引</param> /// <param name="endColumnIndex">結束列索引</param> /// <param name="text">合並后Range的值</param> public void MergeCells(int sheetIndex, int beginRowIndex, int beginColumnIndex, int endRowIndex, int endColumnIndex, string text) { if (sheetIndex > this.WorkSheetCount) { this.KillExcelProcess(false); throw new Exception("索引超出范圍,WorkSheet索引不能大於WorkSheet數量!"); } workSheet = (Excel.Worksheet)workBook.Worksheets.get_Item(sheetIndex); range = workSheet.get_Range(workSheet.Cells[beginRowIndex, beginColumnIndex], workSheet.Cells[endRowIndex, endColumnIndex]); range.ClearContents(); //先把Range內容清除,合並才不會出錯 range.MergeCells = true; range.Value2 = text; range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; range.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter; } #endregion #region Row Methods /// <summary> /// 將指定索引列的數據相同的行合並,對每個WorkSheet操作 /// </summary> /// <param name="columnIndex">列索引</param> /// <param name="beginRowIndex">開始行索引</param> /// <param name="endRowIndex">結束行索引</param> public void MergeRows(int columnIndex, int beginRowIndex, int endRowIndex) { if (endRowIndex - beginRowIndex < 1) return; for (int i = 1; i <= this.WorkSheetCount; i++) { int beginIndex = beginRowIndex; int count = 0; string text1; string text2; workSheet = (Excel.Worksheet)workBook.Worksheets.get_Item(i); for (int j = beginRowIndex; j <= endRowIndex; j++) { range = (Excel.Range)workSheet.Cells[j, columnIndex]; text1 = range.Text.ToString(); range = (Excel.Range)workSheet.Cells[j + 1, columnIndex]; text2 = range.Text.ToString(); if (text1 == text2) { ++count; } else { if (count > 0) { this.MergeCells(workSheet, beginIndex, columnIndex, beginIndex + count, columnIndex, text1); } beginIndex = j + 1; //設置開始合並行索引 count = 0; //計數器清0 } } } } /// <summary> /// 將指定索引列的數據相同的行合並,對指定WorkSheet操作 /// </summary> /// <param name="sheetIndex">WorkSheet索引</param> /// <param name="columnIndex">列索引</param> /// <param name="beginRowIndex">開始行索引</param> /// <param name="endRowIndex">結束行索引</param> public void MergeRows(int sheetIndex, int columnIndex, int beginRowIndex, int endRowIndex) { if (sheetIndex > this.WorkSheetCount) { this.KillExcelProcess(false); throw new Exception("索引超出范圍,WorkSheet索引不能大於WorkSheet數量!"); } if (endRowIndex - beginRowIndex < 1) return; int beginIndex = beginRowIndex; int count = 0; string text1; string text2; workSheet = (Excel.Worksheet)workBook.Worksheets.get_Item(sheetIndex); for (int j = beginRowIndex; j <= endRowIndex; j++) { range = (Excel.Range)workSheet.Cells[j, columnIndex]; text1 = range.Text.ToString(); range = (Excel.Range)workSheet.Cells[j + 1, columnIndex]; text2 = range.Text.ToString(); if (text1 == text2) { ++count; } else { if (count > 0) { this.MergeCells(workSheet, beginIndex, columnIndex, beginIndex + count, columnIndex, text1); } beginIndex = j + 1; //設置開始合並行索引 count = 0; //計數器清0 } } } /// <summary> /// 插行(在指定行上面插入指定數量行) /// </summary> /// <param name="rowIndex"></param> /// <param name="count"></param> public void InsertRows(int rowIndex, int count) { try { for (int n = 1; n <= this.WorkSheetCount; n++) { workSheet = (Excel.Worksheet)workBook.Worksheets[n]; range = (Excel.Range)workSheet.Rows[rowIndex, this.missing]; for (int i = 0; i < count; i++) { range.Insert(Excel.XlDirection.xlDown, missing); } } } catch (Exception e) { this.KillExcelProcess(false); throw e; } } /// <summary> /// 插行(在指定WorkSheet指定行上面插入指定數量行) /// </summary> /// <param name="sheetIndex"></param> /// <param name="rowIndex"></param> /// <param name="count"></param> public void InsertRows(int sheetIndex, int rowIndex, int count) { if (sheetIndex > this.WorkSheetCount) { this.KillExcelProcess(false); throw new Exception("索引超出范圍,WorkSheet索引不能大於WorkSheet數量!"); } try { workSheet = (Excel.Worksheet)workBook.Worksheets[sheetIndex]; range = (Excel.Range)workSheet.Rows[rowIndex, this.missing]; for (int i = 0; i < count; i++) { range.Insert(Excel.XlDirection.xlDown, missing); } } catch (Exception e) { this.KillExcelProcess(false); throw e; } } /// <summary> /// 復制行(在指定行下面復制指定數量行) /// </summary> /// <param name="rowIndex"></param> /// <param name="count"></param> public void CopyRows(int rowIndex, int count) { try { for (int n = 1; n <= this.WorkSheetCount; n++) { workSheet = (Excel.Worksheet)workBook.Worksheets[n]; range1 = (Excel.Range)workSheet.Rows[rowIndex, this.missing]; for (int i = 1; i <= count; i++) { range2 = (Excel.Range)workSheet.Rows[rowIndex + i, this.missing]; range1.Copy(range2); } } } catch (Exception e) { this.KillExcelProcess(false); throw e; } } /// <summary> /// 復制行(在指定WorkSheet指定行下面復制指定數量行) /// </summary> /// <param name="sheetIndex"></param> /// <param name="rowIndex"></param> /// <param name="count"></param> public void CopyRows(int sheetIndex, int rowIndex, int count) { if (sheetIndex > this.WorkSheetCount) { this.KillExcelProcess(false); throw new Exception("索引超出范圍,WorkSheet索引不能大於WorkSheet數量!"); } try { workSheet = (Excel.Worksheet)workBook.Worksheets[sheetIndex]; range1 = (Excel.Range)workSheet.Rows[rowIndex, this.missing]; for (int i = 1; i <= count; i++) { range2 = (Excel.Range)workSheet.Rows[rowIndex + i, this.missing]; range1.Copy(range2); } } catch (Exception e) { this.KillExcelProcess(false); throw e; } } /// <summary> /// 刪除行 /// </summary> /// <param name="rowIndex"></param> /// <param name="count"></param> public void DeleteRows(int rowIndex, int count) { try { for (int n = 1; n <= this.WorkSheetCount; n++) { workSheet = (Excel.Worksheet)workBook.Worksheets[n]; range = (Excel.Range)workSheet.Rows[rowIndex, this.missing]; for (int i = 0; i < count; i++) { range.Delete(Excel.XlDirection.xlDown); } } } catch (Exception e) { this.KillExcelProcess(false); throw e; } } /// <summary> /// 刪除行 /// </summary> /// <param name="sheetIndex"></param> /// <param name="rowIndex"></param> /// <param name="count"></param> public void DeleteRows(int sheetIndex, int rowIndex, int count) { if (sheetIndex > this.WorkSheetCount) { this.KillExcelProcess(false); throw new Exception("索引超出范圍,WorkSheet索引不能大於WorkSheet數量!"); } try { workSheet = (Excel.Worksheet)workBook.Worksheets[sheetIndex]; range = (Excel.Range)workSheet.Rows[rowIndex, this.missing]; for (int i = 0; i < count; i++) { range.Delete(Excel.XlDirection.xlDown); } } catch (Exception e) { this.KillExcelProcess(false); throw e; } } #endregion #region Column Methods /// <summary> /// 插列(在指定列右邊插入指定數量列) /// </summary> /// <param name="columnIndex"></param> /// <param name="count"></param> public void InsertColumns(int columnIndex, int count) { try { for (int n = 1; n <= this.WorkSheetCount; n++) { workSheet = (Excel.Worksheet)workBook.Worksheets[n]; range = (Excel.Range)workSheet.Columns[this.missing, columnIndex]; for (int i = 0; i < count; i++) { range.Insert(Excel.XlDirection.xlDown, missing); } } } catch (Exception e) { this.KillExcelProcess(false); throw e; } } /// <summary> /// 插列(在指定WorkSheet指定列右邊插入指定數量列) /// </summary> /// <param name="sheetIndex"></param> /// <param name="columnIndex"></param> /// <param name="count"></param> public void InsertColumns(int sheetIndex, int columnIndex, int count) { if (sheetIndex > this.WorkSheetCount) { this.KillExcelProcess(false); throw new Exception("索引超出范圍,WorkSheet索引不能大於WorkSheet數量!"); } try { workSheet = (Excel.Worksheet)workBook.Worksheets[sheetIndex]; range = (Excel.Range)workSheet.Columns[this.missing, columnIndex]; for (int i = 0; i < count; i++) { range.Insert(Excel.XlDirection.xlDown, missing); } } catch (Exception e) { this.KillExcelProcess(false); throw e; } } /// <summary> /// 復制列(在指定列右邊復制指定數量列) /// </summary> /// <param name="columnIndex"></param> /// <param name="count"></param> public void CopyColumns(int columnIndex, int count) { try { for (int n = 1; n <= this.WorkSheetCount; n++) { workSheet = (Excel.Worksheet)workBook.Worksheets[n]; // range1 = (Excel.Range)workSheet.Columns[columnIndex,this.missing]; range1 = (Excel.Range)workSheet.get_Range(this.IntToLetter(columnIndex) + "1", this.IntToLetter(columnIndex) + "10000"); for (int i = 1; i <= count; i++) { // range2 = (Excel.Range)workSheet.Columns[this.missing,columnIndex + i]; range2 = (Excel.Range)workSheet.get_Range(this.IntToLetter(columnIndex + i) + "1", this.IntToLetter(columnIndex + i) + "10000"); range1.Copy(range2); } } } catch (Exception e) { this.KillExcelProcess(false); throw e; } } /// <summary> /// 復制列(在指定WorkSheet指定列右邊復制指定數量列) /// </summary> /// <param name="sheetIndex"></param> /// <param name="columnIndex"></param> /// <param name="count"></param> public void CopyColumns(int sheetIndex, int columnIndex, int count) { if (sheetIndex > this.WorkSheetCount) { this.KillExcelProcess(false); throw new Exception("索引超出范圍,WorkSheet索引不能大於WorkSheet數量!"); } try { workSheet = (Excel.Worksheet)workBook.Worksheets[sheetIndex]; // range1 = (Excel.Range)workSheet.Columns[Type.Missing,columnIndex]; range1 = (Excel.Range)workSheet.get_Range(this.IntToLetter(columnIndex) + "1", this.IntToLetter(columnIndex) + "10000"); for (int i = 1; i <= count; i++) { // range2 = (Excel.Range)workSheet.Columns[Type.Missing,columnIndex + i]; range2 = (Excel.Range)workSheet.get_Range(this.IntToLetter(columnIndex + i) + "1", this.IntToLetter(columnIndex + i) + "10000"); range1.Copy(range2); } } catch (Exception e) { this.KillExcelProcess(false); throw e; } } /// <summary> /// 刪除列 /// </summary> /// <param name="columnIndex"></param> /// <param name="count"></param> public void DeleteColumns(int columnIndex, int count) { try { for (int n = 1; n <= this.WorkSheetCount; n++) { workSheet = (Excel.Worksheet)workBook.Worksheets[n]; range = (Excel.Range)workSheet.Columns[this.missing, columnIndex]; for (int i = 0; i < count; i++) { range.Delete(Excel.XlDirection.xlDown); } } } catch (Exception e) { this.KillExcelProcess(false); throw e; } } /// <summary> /// 刪除列 /// </summary> /// <param name="sheetIndex"></param> /// <param name="columnIndex"></param> /// <param name="count"></param> public void DeleteColumns(int sheetIndex, int columnIndex, int count) { if (sheetIndex > this.WorkSheetCount) { this.KillExcelProcess(false); throw new Exception("索引超出范圍,WorkSheet索引不能大於WorkSheet數量!"); } try { workSheet = (Excel.Worksheet)workBook.Worksheets[sheetIndex]; range = (Excel.Range)workSheet.Columns[this.missing, columnIndex]; for (int i = 0; i < count; i++) { range.Delete(Excel.XlDirection.xlDown); } } catch (Exception e) { this.KillExcelProcess(false); throw e; } } #region 通過列數獲取excel列名 public String GetColumnName(int num) { String[] COL_NAME = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" }; int a = 0, b = num; String col = ""; if (b < 26) { col = COL_NAME[b]; } else { while (b >= 26) { a = b % 26; b = b / 26; col = COL_NAME[a] + col; } col = COL_NAME[b - 1] + col; } return col; } #endregion #endregion #region Range Methods /// <summary> /// 將指定范圍區域拷貝到目標區域 /// </summary> /// <param name="sheetIndex">WorkSheet索引</param> /// <param name="startCell">要拷貝區域的開始Cell位置(比如:A10)</param> /// <param name="endCell">要拷貝區域的結束Cell位置(比如:F20)</param> /// <param name="targetCell">目標區域的開始Cell位置(比如:H10)</param> public void RangeCopy(int sheetIndex, string startCell, string endCell, string targetCell) { if (sheetIndex > this.WorkSheetCount) { this.KillExcelProcess(false); throw new Exception("索引超出范圍,WorkSheet索引不能大於WorkSheet數量!"); } try { workSheet = (Excel.Worksheet)workBook.Worksheets.get_Item(sheetIndex); range1 = workSheet.get_Range(startCell, endCell); range2 = workSheet.get_Range(targetCell, this.missing); range1.Copy(range2); } catch (Exception e) { this.KillExcelProcess(false); throw e; } } /// <summary> /// 將指定范圍區域拷貝到目標區域 /// </summary> /// <param name="sheetName">WorkSheet名稱</param> /// <param name="startCell">要拷貝區域的開始Cell位置(比如:A10)</param> /// <param name="endCell">要拷貝區域的結束Cell位置(比如:F20)</param> /// <param name="targetCell">目標區域的開始Cell位置(比如:H10)</param> public void RangeCopy(string sheetName, string startCell, string endCell, string targetCell) { try { Excel.Worksheet sheet = null; for (int i = 1; i <= this.WorkSheetCount; i++) { workSheet = (Excel.Worksheet)workBook.Sheets.get_Item(i); if (workSheet.Name == sheetName) { sheet = workSheet; } } if (sheet != null) { for (int i = sheetCount; i >= 1; i--) { range1 = sheet.get_Range(startCell, endCell); range2 = sheet.get_Range(targetCell, this.missing); range1.Copy(range2); } } else { this.KillExcelProcess(false); throw new Exception("名稱為\"" + sheetName + "\"的工作表不存在"); } } catch (Exception e) { this.KillExcelProcess(false); throw e; } } /// <summary> /// 自動填充 /// </summary> public void RangAutoFill() { Excel.Range rng = workSheet.get_Range("B4", Type.Missing); rng.Value2 = "星期一 "; rng.AutoFill(workSheet.get_Range("B4", "B9"), Excel.XlAutoFillType.xlFillWeekdays); rng = workSheet.get_Range("C4", Type.Missing); rng.Value2 = "一月"; rng.AutoFill(workSheet.get_Range("C4", "C9"), Excel.XlAutoFillType.xlFillMonths); rng = workSheet.get_Range("D4", Type.Missing); rng.Value2 = "1"; rng.AutoFill(workSheet.get_Range("D4", "D9"), Excel.XlAutoFillType.xlFillSeries); rng = workSheet.get_Range("E4", Type.Missing); rng.Value2 = "3"; rng = workSheet.get_Range("E5", Type.Missing); rng.Value2 = "6"; rng = workSheet.get_Range("E4", "E5"); rng.AutoFill(workSheet.get_Range("E4", "E9"), Excel.XlAutoFillType.xlFillSeries); } /// <summary> /// 應用樣式 /// </summary> public void ApplyStyle() { object missingValue = Type.Missing; Excel.Range rng = workSheet.get_Range("B3", "L23"); Excel.Style style; try { style = workBook.Styles["NewStyle"]; } // Style doesn't exist yet. catch { style = workBook.Styles.Add("NewStyle", missingValue); style.Font.Name = "Verdana"; style.Font.Size = 12; style.Font.Color = 255; style.Interior.Color = (200 << 16) | (200 << 8) | 200; style.Interior.Pattern = Excel.XlPattern.xlPatternSolid; } rng.Value2 = "'Style Test"; rng.Style = "NewStyle"; rng.Columns.AutoFit(); } #endregion #region Set Style Methods /// <summary> /// 單元格背景色及填充方式 /// </summary> /// <param name="startRow">起始行</param> /// <param name="startColumn">起始列</param> /// <param name="endRow">結束行</param> /// <param name="endColumn">結束列</param> /// <param name="color">顏色索引</param> public void CellsBackColor(int startRow, int startColumn, int endRow, int endColumn, ColorIndex color) { Excel.Range range = excelApp.get_Range(excelApp.Cells[startRow, startColumn], excelApp.Cells[endRow, endColumn]); range.Interior.ColorIndex = color; range.Interior.Pattern = Pattern.Solid; } /// <summary> /// 單元格背景色及填充方式 /// </summary> /// <param name="startRow">起始行</param> /// <param name="startColumn">起始列</param> /// <param name="endRow">結束行</param> /// <param name="endColumn">結束列</param> /// <param name="color">顏色索引</param> /// <param name="pattern">填充方式</param> public void CellsBackColor(int startRow, int startColumn, int endRow, int endColumn, ColorIndex color, Pattern pattern) { Excel.Range range = excelApp.get_Range(excelApp.Cells[startRow, startColumn], excelApp.Cells[endRow, endColumn]); range.Interior.ColorIndex = color; range.Interior.Pattern = pattern; } /// <summary> /// 設置行高 /// </summary> /// <param name="startRow">起始行</param> /// <param name="endRow">結束行</param> /// <param name="height">行高</param> public void SetRowHeight(int startRow, int endRow, int height) { //獲取當前正在使用的工作表 Excel.Worksheet worksheet = (Excel.Worksheet)excelApp.ActiveSheet; Excel.Range range = (Excel.Range)worksheet.Rows[startRow.ToString() + ":" + endRow.ToString(), System.Type.Missing]; range.RowHeight = height; } /// <summary> /// 自動調整行高 /// </summary> /// <param name="columnNum">列號</param> public void RowAutoFit(int rowNum) { //獲取當前正在使用的工作表 Excel.Worksheet worksheet = (Excel.Worksheet)excelApp.ActiveSheet; Excel.Range range = (Excel.Range)worksheet.Rows[rowNum.ToString() + ":" + rowNum.ToString(), System.Type.Missing]; range.EntireColumn.AutoFit(); } /// <summary> /// 設置列寬 /// </summary> /// <param name="startColumn">起始列(列對應的字母)</param> /// <param name="endColumn">結束列(列對應的字母)</param> /// <param name="width"></param> public void SetColumnWidth(string startColumn, string endColumn, int width) { //獲取當前正在使用的工作表 Excel.Worksheet worksheet = (Excel.Worksheet)excelApp.ActiveSheet; Excel.Range range = (Excel.Range)worksheet.Columns[startColumn + ":" + endColumn, System.Type.Missing]; range.ColumnWidth = width; } /// <summary> /// 設置列寬 /// </summary> /// <param name="startColumn">起始列</param> /// <param name="endColumn">結束列</param> /// <param name="width"></param> public void SetColumnWidth(int startColumn, int endColumn, int width) { string strStartColumn = GetColumnName(startColumn); string strEndColumn = GetColumnName(endColumn); //獲取當前正在使用的工作表 Excel.Worksheet worksheet = (Excel.Worksheet)excelApp.ActiveSheet; Excel.Range range = (Excel.Range)worksheet.Columns[strStartColumn + ":" + strEndColumn, System.Type.Missing]; range.ColumnWidth = width; } /// <summary> /// 自動調整列寬 /// </summary> /// <param name="columnNum">列號</param> public void ColumnAutoFit(string column) { //獲取當前正在使用的工作表 Excel.Worksheet worksheet = (Excel.Worksheet)excelApp.ActiveSheet; Excel.Range range = (Excel.Range)worksheet.Columns[column + ":" + column, System.Type.Missing]; range.EntireColumn.AutoFit(); } /// <summary> /// 自動調整列寬 /// </summary> /// <param name="columnNum">列號</param> public void ColumnAutoFit(int columnNum) { string strcolumnNum = GetColumnName(columnNum); //獲取當前正在使用的工作表 Excel.Worksheet worksheet = (Excel.Worksheet)excelApp.ActiveSheet; Excel.Range range = (Excel.Range)worksheet.Columns[strcolumnNum + ":" + strcolumnNum, System.Type.Missing]; range.EntireColumn.AutoFit(); } /// <summary> /// 字體顏色 /// </summary> /// <param name="startRow">起始行</param> /// <param name="startColumn">起始列</param> /// <param name="endRow">結束行</param> /// <param name="endColumn">結束列</param> /// <param name="color">顏色索引</param> public void FontColor(int startRow, int startColumn, int endRow, int endColumn, ColorIndex color) { Excel.Range range = excelApp.get_Range(excelApp.Cells[startRow, startColumn], excelApp.Cells[endRow, endColumn]); range.Font.ColorIndex = color; } /// <summary> /// 字體樣式(加粗,斜體,下划線) /// </summary> /// <param name="startRow">起始行</param> /// <param name="startColumn">起始列</param> /// <param name="endRow">結束行</param> /// <param name="endColumn">結束列</param> /// <param name="isBold">是否加粗</param> /// <param name="isItalic">是否斜體</param> /// <param name="underline">下划線類型</param> public void FontStyle(int startRow, int startColumn, int endRow, int endColumn, bool isBold, bool isItalic, UnderlineStyle underline) { Excel.Range range = excelApp.get_Range(excelApp.Cells[startRow, startColumn], excelApp.Cells[endRow, endColumn]); range.Font.Bold = isBold; range.Font.Underline = underline; range.Font.Italic = isItalic; } /// <summary> /// 單元格字體及大小 /// </summary> /// <param name="startRow">起始行</param> /// <param name="startColumn">起始列</param> /// <param name="endRow">結束行</param> /// <param name="endColumn">結束列</param> /// <param name="fontName">字體名稱</param> /// <param name="fontSize">字體大小</param> public void FontNameSize(int startRow, int startColumn, int endRow, int endColumn, string fontName, int fontSize) { Excel.Range range = excelApp.get_Range(excelApp.Cells[startRow, startColumn], excelApp.Cells[endRow, endColumn]); range.Font.Name = fontName; range.Font.Size = fontSize; } #endregion #region 列頭轉換 /// <summary> /// 最大列數 /// 2007:16384 /// 2003:256 /// </summary> int MaxColumnCount = 16384; /// <summary> /// 將Excel列的字母索引值轉換成整數索引值 /// </summary> /// <param name="letter"></param> /// <returns></returns> public int LetterToInt(string letter) { int n = 0; if (letter.Trim().Length == 0) throw new Exception("不接受空字符串!"); if (letter.Length == 1) { char c1 = letter.ToCharArray()[0]; if (!char.IsLetter(c1)) { throw new Exception("格式不正確,必須是字母!"); } c1 = char.ToUpper(c1); n = Convert.ToInt32(c1) - 64; } else { char[] chs = letter.ToCharArray(); for (int i = 0; i < chs.Length; i++) { if (!char.IsLetter(chs[i])) { throw new Exception("格式不正確,必須是字母!"); } char ctemp = char.ToUpper(chs[i]); int col = Convert.ToInt32(ctemp) - 64; n += Convert.ToInt32(Math.Pow(26, (chs.Length - i - 1))) * col; if (n > MaxColumnCount) throw new Exception(string.Format("索引超出范圍,Excel的列索引不能超過{0}!", MaxColumnCount)); } } return n; } /// <summary> /// 將Excel列的整數索引值轉換為字符索引值 /// </summary> /// <param name="n"></param> /// <returns></returns> public string IntToLetter(int n) { if (n > MaxColumnCount) throw new Exception(string.Format("索引超出范圍,Excel的列索引不能超過{0}!", MaxColumnCount)); String[] COL_NAME = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" }; int a = 0, b = n; String col = ""; if (b < 26) { col = COL_NAME[b]; } else { while (b >= 26) { a = b % 26; b = b / 26; col = COL_NAME[a] + col; } col = COL_NAME[b - 1] + col; } return col; } #endregion #region Output File(注意:如果目標文件已存在的話會出錯) /// <summary> /// 輸出Excel文件並退出 /// </summary> public void OutputExcelFile() { if (this.outputFile == null) throw new Exception("沒有指定輸出文件路徑!"); try { workBook.SaveAs(outputFile, missing, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing); } catch (Exception e) { throw e; } finally { this.Quit(); } } /// <summary> /// 輸出指定格式的文件(支持格式:HTML,CSV,TEXT,EXCEL) /// </summary> /// <param name="format">HTML,CSV,TEXT,EXCEL,XML</param> public void OutputFile(string format) { if (this.outputFile == null) throw new Exception("沒有指定輸出文件路徑!"); try { switch (format) { case "HTML": { workBook.SaveAs(outputFile, Excel.XlFileFormat.xlHtml, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing); break; } case "CSV": { workBook.SaveAs(outputFile, Excel.XlFileFormat.xlCSV, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing); break; } case "TEXT": { workBook.SaveAs(outputFile, Excel.XlFileFormat.xlHtml, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing); break; } // case "XML": // { // workBook.SaveAs(outputFile,Excel.XlFileFormat.xlXMLSpreadsheet, Type.Missing, Type.Missing, // Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, // Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); // break; // // } default: { workBook.SaveAs(outputFile, missing, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing); break; } } } catch (Exception e) { throw e; } finally { this.Quit(); } } /// <summary> /// 保存文件 /// </summary> public void SaveFile() { try { workBook.Save(); } catch (Exception e) { throw e; } finally { this.Quit(); } } /// <summary> /// 另存文件 /// </summary> public void SaveAsFile() { if (this.outputFile == null) throw new Exception("沒有指定輸出文件路徑!"); try { workBook.SaveAs(outputFile, missing, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing); } catch (Exception e) { throw e; } finally { this.Quit(); } } /// <summary> /// 將Excel文件另存為指定格式 /// </summary> /// <param name="format">HTML,CSV,TEXT,EXCEL,XML</param> public void SaveAsFile(string format) { if (this.outputFile == null) throw new Exception("沒有指定輸出文件路徑!"); try { switch (format) { case "HTML": { workBook.SaveAs(outputFile, Excel.XlFileFormat.xlHtml, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing); break; } case "CSV": { workBook.SaveAs(outputFile, Excel.XlFileFormat.xlCSV, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing); break; } case "TEXT": { workBook.SaveAs(outputFile, Excel.XlFileFormat.xlHtml, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing); break; } // case "XML": // { // workBook.SaveAs(outputFile,Excel.XlFileFormat.xlXMLSpreadsheet, Type.Missing, Type.Missing, // Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, // Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); // break; // } default: { workBook.SaveAs(outputFile, missing, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing); break; } } } catch (Exception e) { throw e; } finally { this.Quit(); } } /// <summary> /// 另存文件 /// </summary> /// <param name="fileName">文件名</param> public void SaveFile(string fileName) { try { workBook.SaveAs(fileName, missing, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing); } catch (Exception e) { throw e; } finally { this.Quit(); } } /// <summary> /// 將Excel文件另存為指定格式 /// </summary> /// <param name="fileName">文件名</param> /// <param name="format">HTML,CSV,TEXT,EXCEL,XML</param> public void SaveAsFile(string fileName, string format) { try { switch (format) { case "HTML": { workBook.SaveAs(fileName, Excel.XlFileFormat.xlHtml, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing); break; } case "CSV": { workBook.SaveAs(fileName, Excel.XlFileFormat.xlCSV, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing); break; } case "TEXT": { workBook.SaveAs(fileName, Excel.XlFileFormat.xlHtml, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing); break; } // case "XML": // { // workBook.SaveAs(fileName,Excel.XlFileFormat.xlXMLSpreadsheet, Type.Missing, Type.Missing, // Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, // Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); // break; // } default: { workBook.SaveAs(fileName, missing, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing); break; } } } catch (Exception e) { throw e; } finally { this.Quit(); } } #endregion #endregion #region 私有方法 /// <summary> /// 合並單元格,並賦值,對指定WorkSheet操作 /// </summary> /// <param name="beginRowIndex">開始行索引</param> /// <param name="beginColumnIndex">開始列索引</param> /// <param name="endRowIndex">結束行索引</param> /// <param name="endColumnIndex">結束列索引</param> /// <param name="text">合並后Range的值</param> private void MergeCells(Excel.Worksheet sheet, int beginRowIndex, int beginColumnIndex, int endRowIndex, int endColumnIndex, string text) { if (sheet == null) return; range = sheet.get_Range(sheet.Cells[beginRowIndex, beginColumnIndex], sheet.Cells[endRowIndex, endColumnIndex]); range.ClearContents(); //先把Range內容清除,合並才不會出錯 range.MergeCells = true; range.Value2 = text; range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; range.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter; } /// <summary> /// 將指定索引列的數據相同的行合並,對指定WorkSheet操作 /// </summary> /// <param name="columnIndex">要合並的列索引</param> /// <param name="beginRowIndex">合並開始行索引</param> /// <param name="rows">要合並的行數</param> private void MergeRows(Excel.Worksheet sheet, int columnIndex, int beginRowIndex, int rows) { int beginIndex = beginRowIndex; int count = 0; string text1; string text2; if (sheet == null) return; for (int j = beginRowIndex; j < beginRowIndex + rows; j++) { range1 = (Excel.Range)sheet.Cells[j, columnIndex]; range2 = (Excel.Range)sheet.Cells[j + 1, columnIndex]; text1 = range1.Text.ToString(); text2 = range2.Text.ToString(); if (text1 == text2) { ++count; } else { if (count > 0) { this.MergeCells(sheet, beginIndex, columnIndex, beginIndex + count, columnIndex, text1); } beginIndex = j + 1; //設置開始合並行索引 count = 0; //計數器清0 } } } /// <summary> /// 計算WorkSheet數量 /// </summary> /// <param name="rowCount">記錄總行數</param> /// <param name="rows">每WorkSheet行數</param> public int GetSheetCount(int rowCount, int rows) { int n = rowCount % rows; //余數 if (n == 0) return rowCount / rows; else return Convert.ToInt32(rowCount / rows) + 1; } /// <summary> /// 結束Excel進程 /// </summary> public void KillExcelProcess(bool bAll) { if (bAll) { Process[] myProcesses; myProcesses = Process.GetProcessesByName("Excel"); //得不到Excel進程ID,暫時只能判斷進程啟動時間 foreach (Process myProcess in myProcesses) { myProcess.Kill(); continue; } } else { KillSpecialExcel(); } } [DllImport("user32.dll", SetLastError = true)] static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId); public void KillSpecialExcel() { try { if (excelApp != null) { int lpdwProcessId; GetWindowThreadProcessId((IntPtr)excelApp.Hwnd, out lpdwProcessId); //c-s方式 if (lpdwProcessId > 0) { System.Diagnostics.Process.GetProcessById(lpdwProcessId).Kill(); } else { Quit(); //excelApp.Quit(); //excelApp = null; //b-s方式windows api失效,進程時間也報win32錯誤 //Process[] myProcesses; //myProcesses = Process.GetProcessesByName("Excel"); //DateTime startTime; //foreach (Process myProcess in myProcesses) { // startTime = myProcess.StartTime; // if (startTime > beforeTime && startTime < afterTime) { // myProcess.Kill(); // } // continue; //} } } } catch { } } public void Quit() { if (workBook != null) workBook.Close(null, null, null); if (excelApp != null) { excelApp.Workbooks.Close(); excelApp.Quit(); } if (range != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(range); range = null; } if (range1 != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(range1); range1 = null; } if (range2 != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(range2); range2 = null; } if (textBox != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(textBox); textBox = null; } if (workSheet != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet); workSheet = null; } if (workBook != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook); workBook = null; } if (excelApp != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp); excelApp = null; } GC.Collect(); }//end Quit #endregion #region get sheets /// <summary> /// 按Index得到WorkSheet /// </summary> /// <param name="index">序號</param> public Excel.Worksheet GetSheet(int index) { try { Excel.Worksheet aimSheet = (Excel.Worksheet)workBook.Sheets.get_Item(index); return aimSheet; } catch (Exception e) { this.KillExcelProcess(false); throw e; } } public Excel.Worksheet GetSheetByName(string strName) { try { for (int i = 1; i <= workBook.Sheets.Count; i++) { workSheet = (Excel.Worksheet)workBook.Sheets.get_Item(i); if (workSheet.Name == strName) return workSheet; } this.KillExcelProcess(false); //throw new Exception("sheet not exist"); return null; } catch (Exception e) { this.KillExcelProcess(false); throw e; } } public List<string> GetSheets() { List<string> listN = new List<string>(); for (int i = 1; i <= workBook.Sheets.Count; i++) { workSheet = (Excel.Worksheet)workBook.Sheets.get_Item(i); listN.Add(workSheet.Name); } return listN; } #endregion #region IDisposable 成員 void IDisposable.Dispose() { Quit(); } #endregion } #region Common Excel Enum Properties /// <summary> /// HTML,CSV,TEXT,EXCEL,XML /// </summary> enum SaveAsFileFormat { HTML, CSV, TEXT, EXCEL, XML } /// <summary> /// 常用顏色定義,對就Excel中顏色名 /// </summary> public enum ColorIndex { 無色 = -4142, 自動 = -4105, 黑色 = 1, 褐色 = 53, 橄欖 = 52, 深綠 = 51, 深青 = 49, 深藍 = 11, 靛藍 = 55, 灰色80 = 56, 深紅 = 9, 橙色 = 46, 深黃 = 12, 綠色 = 10, 青色 = 14, 藍色 = 5, 藍灰 = 47, 灰色50 = 16, 紅色 = 3, 淺橙色 = 45, 酸橙色 = 43, 海綠 = 50, 水綠色 = 42, 淺藍 = 41, 紫羅蘭 = 13, 灰色40 = 48, 粉紅 = 7, 金色 = 44, 黃色 = 6, 鮮綠 = 4, 青綠 = 8, 天藍 = 33, 梅紅 = 54, 灰色25 = 15, 玫瑰紅 = 38, 茶色 = 40, 淺黃 = 36, 淺綠 = 35, 淺青綠 = 34, 淡藍 = 37, 淡紫 = 39, 白色 = 2 } /// <summary> /// 水平對齊方式 /// </summary> public enum ExcelHAlign { 常規 = 1, 靠左, 居中, 靠右, 填充, 兩端對齊, 跨列居中, 分散對齊 } /// <summary> /// 垂直對齊方式 /// </summary> public enum ExcelVAlign { 靠上 = 1, 居中, 靠下, 兩端對齊, 分散對齊 } /// <summary> /// 線粗 /// </summary> public enum BorderWeight { 極細 = 1, 細 = 2, 粗 = -4138, 極粗 = 4 } /// <summary> /// 線樣式 /// </summary> public enum LineStyle { 連續直線 = 1, 短線 = -4115, 線點相間 = 4, 短線間兩點 = 5, 點 = -4118, 雙線 = -4119, 無 = -4142, 少量傾斜點 = 13 } /// <summary> /// 下划線方式 /// </summary> public enum UnderlineStyle { 無下划線 = -4142, 雙線 = -4119, 雙線充滿全格 = 5, 單線 = 2, 單線充滿全格 = 4 } /// <summary> /// 單元格填充方式 /// </summary> public enum Pattern { Automatic = -4105, Checker = 9, CrissCross = 16, Down = -4121, Gray16 = 17, Gray25 = -4124, Gray50 = -4125, Gray75 = -4126, Gray8 = 18, Grid = 15, Horizontal = -4128, LightDown = 13, LightHorizontal = 11, LightUp = 14, LightVertical = 12, None = -4142, SemiGray75 = 10, Solid = 1, Up = -4162, Vertical = -4166 } #endregion }