ExcelHelper
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; using System.IO; //File using System.Diagnostics;//Process using System.Reflection;//引用这个才能使用Missing字段 using Excel = Microsoft.Office.Interop.Excel; //操作Excel using System.Data;//DataTable using System.Data.SqlClient; //sqlserver数据库连接 using System.Data.OleDb; using System.Text.RegularExpressions; //Regex using System.Data.OleDb; //OleDbDataAdapter namespace MyExcel { public class ExcelHelper { #region 变量 private Excel.Application ExApp = null; //引擎 private Excel.Workbook wb = null; //工作薄 private Excel.Workbooks wbs = null; //工作薄(集合) private Excel.Worksheet ws = null; //工作表 private Excel.Worksheets wss = null; //工作表(集合) private int workSheetCount = 0; //WorkSheet数量 private object missing = Missing.Value; //使用 Missing 类的此实例来表示缺少的值 private Excel.Range getRange; //代表一个Excel单元格 private Excel.Range changeRange; /// <summary> /// 代表一个Excel单元格 /// </summary> public Excel.Range ChangeRange { get { return changeRange; } set { changeRange = value; } } /// <summary> /// 代表一个Excel单元格 /// </summary> public Excel.Range GetRange { get { return getRange; } set { getRange = value; } } private string inputPath; //输入文件路径 public string InputPath { get { return inputPath; } set { inputPath = value; } } string outputPath; //文件输出路径 public string OutputPath { get { return outputPath; } set { outputPath = value; } } DateTime beforeTime;//Excel启动之前时间 DateTime afterTime; //Excel启动之后时间 private string[] arry = new string[] { }; //数组 /// <summary> /// 数组 /// </summary> public string[] Arry { get { return arry; } set { arry = value; } } #endregion /// <summary> /// 构造函数 /// </summary> public ExcelHelper() {} /// <summary> /// 初始化 /// </summary> /// <param name="inputFilePath">Excel模板路径</param> public ExcelHelper(string inputFilePath) { if (string.IsNullOrEmpty(inputFilePath)) throw new Exception("Excel模板文件路径不能为空!"); if (!File.Exists(inputFilePath)) throw new Exception("指定路径的Excel模板文件不存在!"); beforeTime = DateTime.Now; //启动时间 try { ExApp = new Excel.Application(); } catch { throw new Exception("先要安装office,才能把数据保存到Excel"); } afterTime = DateTime.Now; //启动结束 try { wb = (Excel.Workbook)ExApp.Workbooks.Open(inputFilePath, Type.Missing, false, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); } catch { throw new Exception("请先关闭Excel模板"); } try { ws = (Excel.Worksheet)wb.Worksheets.get_Item(1); } catch { throw new Exception("该Excel模板已被损坏"); } workSheetCount = wb.Worksheets.Count; this.inputPath = inputFilePath; } /// <summary> /// 初始化 /// </summary> /// <param name="inputFilePath">Excel模板路径</param> /// <param name="outPutFilePath">保存路径</param> public ExcelHelper(string inputFilePath, string outPutFilePath) { if (string.IsNullOrEmpty(inputFilePath)) throw new Exception("Excel模板文件路径不能为空!"); if (string.IsNullOrEmpty(outPutFilePath)) throw new Exception("输出Excel文件路径不能为空!"); if (!File.Exists(inputFilePath)) throw new Exception("指定路径的Excel模板文件不存在!"); beforeTime = DateTime.Now; //启动时间 try { ExApp = new Excel.Application(); } catch { throw new Exception("先要安装office,才能把数据保存到Excel"); } afterTime = DateTime.Now; //启动结束 try { wb = (Excel.Workbook)ExApp.Workbooks.Open(inputFilePath, Type.Missing, false, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); } catch { throw new Exception("请先关闭Excel模板"); } try { ws = (Excel.Worksheet)wb.Worksheets.get_Item(1); } catch { throw new Exception("该Excel模板已被损坏"); } workSheetCount = wb.Worksheets.Count; this.inputPath = inputFilePath; this.outputPath = outPutFilePath; } #region 公用方法 /// <summary> /// 创建工作薄 /// </summary> public void CreateWorkbooks() { ExApp = new Excel.Application(); ExApp.Workbooks.Add(true); //ExApp.Worksheets.Add(missing, missing, 2, true); ExApp.Visible = true; } /// <summary> /// 添加工作薄 /// </summary> /// <param name="count">个数</param> public void AddWorkbooks(int count) { wb.Worksheets.Add(missing, missing, count, true); } /// <summary> /// 设置值 /// </summary> /// <param name="area">区域: A2</param> /// <param name="value">值</param> public void SetRandValue(string area, string value) { Excel.Range cells = ws.get_Range(area); cells.Value = value; } /// <summary> /// 设置值 /// </summary> /// <param name="row">行</param> /// <param name="col">列</param> /// <param name="value">值</param> public void SetRandValue(int row, int col, string value) { ws = (Excel.Worksheet)wb.Sheets.get_Item(1); ws.Cells[row, col] = value; } /// <summary> /// 设置值 /// </summary> /// <param name="wsName">工作薄名称</param> /// <param name="row">行</param> /// <param name="col">列</param> /// <param name="value">值</param> public void SetRandValue(string wsName, int row, int col, string value) { ws = (Excel.Worksheet)wb.Sheets[wsName]; ws.Cells[row, col] = value; } /// <summary> /// 获取某个工作薄中的某个单元格的值 /// </summary> /// <param name="wsName">工作薄的名称(比如:"Sheet1")</param> /// <param name="range">单元格(比如:D4)</param> /// <returns></returns> public string GetRangValue(string wsName, string range) { ws = (Excel.Worksheet)wb.Sheets[wsName]; getRange = ws.get_Range(range, Type.Missing); return getRange.Text.ToString(); } /// <summary> /// 获取某个工作薄中的某个单元格的值 /// </summary> /// <param name="wsName">工作薄的名称(比如:"Sheet1")</param> /// <param name="row">第几行</param> /// <param name="col">第几列</param> /// <returns></returns> public string GetRangValue(string wsName,int row,int col) { ws = (Excel.Worksheet)wb.Sheets[wsName]; getRange = ws.Cells[row, col]; return getRange.Text.ToString(); } /// <summary> /// 将DataTable填充到Excel中 /// </summary> /// <param name="ShetName">工作薄的名称</param> /// <param name="row">开始行</param> /// <param name="col">开始列</param> /// <param name="dt">DataTable</param> public void PaddingRange(string ShetName, int row, int col,DataTable dt) { ws = (Excel.Worksheet)wb.Sheets[ShetName]; string rowCode = IndexToColumn(col); string colCode = IndexToColumn(dt.Columns.Count+row); string area = rowCode + row + ":" + colCode + (dt.Rows.Count + row - 1); object[,] arr = DataTable_To_Array(dt); Excel.Range range = ws.get_Range(area); range.Value2 = arr; } /// <summary> /// 将DataTable填充到Excel中 /// </summary> /// <param name="dt"></param> public void PaddingRange(DataTable dt) { ws = (Excel.Worksheet)wb.Sheets.get_Item(1); string colCode = IndexToColumn(dt.Columns.Count); string area = "A1:" + colCode + dt.Rows.Count; object[,] arr = DataTable_To_Array(dt); Excel.Range range = ws.get_Range(area); range.Value2 = arr; } /// <summary> /// 清空 sheet /// </summary> /// <param name="ShetName"></param> public void ClearSheet(string ShetName) { ws = (Excel.Worksheet)wb.Sheets[ShetName]; ws.ClearArrows(); } /// <summary> /// 删除 sheet /// </summary> /// <param name="ShetName"></param> public void DeleteSheet(string ShetName) { ws = (Excel.Worksheet)wb.Sheets[ShetName]; ws.Delete(); } /// <summary> /// 将 DataTable 转化为二维数组 /// </summary> /// <param name="table">DataTable</param> /// <returns></returns> public object[,] DataTable_To_Array(DataTable table) { int row = table.Rows.Count; int col = table.Columns.Count; object[,] arr = new object[row, col]; for (int i = 0; i < col; i++) { for (int j = 0; j < row; j++) { arr[j, i] = table.Rows[j][i]; } } return arr; } /// <summary> /// 将 DataRow 转化为二维数组 /// </summary> /// <param name="rows">DataRow</param> /// <returns></returns> public object[,] DataTable_To_Array(DataRow[] rows) { int row = rows.Length; int col = 3; object[,] arr = new object[row, col]; for (int i = 0; i < col; i++) { for (int j = 0; j < row; j++) { arr[j, i] = rows[j][i + 1].ToString(); } } return arr; } /// <summary> /// 将二维数组 转化为 Range /// </summary> /// <param name="arr"></param> /// <param name="area">区域 如 "B5:E40" 区域必须和数组对应</param> /// <returns></returns> public Excel.Range Array_To_Range(object[,] arr, string area) { Excel.Range cells = ws.get_Range(area); cells.Value2 = arr; return cells; } /// <summary> /// 删除列 /// </summary> /// <param name="column">列数</param> /// <returns></returns> public bool DelectCol(int column) { bool flg = false; if (!flg) { ws = (Excel.Worksheet)wb.Sheets[1]; ws.Columns.Delete(column); flg = true; } return flg; } /// <summary> /// 删除列 /// </summary> /// <param name="ShetName">工作薄名称</param> /// <param name="column">列数</param> /// <returns></returns> public bool DelectCol(string ShetName, int column) { bool flg = false; if (!flg) { ws = (Excel.Worksheet)wb.Sheets[ShetName]; ws.Columns.Delete(column); flg = true; } return flg; } /// <summary> /// 删除列 /// </summary> /// <param name="ColNum">第几列</param> /// <returns></returns> public bool DeleteCol(int ColNum) { ((Excel.Range)ws.Cells[1, ColNum]).Select(); ((Excel.Range)ws.Cells[1, ColNum]).EntireColumn.Delete(0); return true; } /// <summary> /// 用于excel表格中列号字母转成列索引,从1对应A开始 /// </summary> /// <param name="column">列号</param> /// <returns>列索引</returns> public int ColumnToIndex(string column) { if (!Regex.IsMatch(column.ToUpper(), @"[A-Z]+")) { throw new Exception("Invalid parameter"); } int index = 0; char[] chars = column.ToUpper().ToCharArray(); for (int i = 0; i < chars.Length; i++) { index += ((int)chars[i] - (int)'A' + 1) * (int)Math.Pow(26, chars.Length - i - 1); } return index; } /// <summary> /// 用于将excel表格中列索引转成列号字母,从A对应1开始 /// </summary> /// <param name="index">列索引</param> /// <returns>列号</returns> public string IndexToColumn(int index) { if (index <= 0) { throw new Exception("Invalid parameter"); } index--; string column = string.Empty; do { if (column.Length > 0) { index--; } column = ((char)(index % 26 + (int)'A')).ToString() + column; index = (int)((index - index % 26) / 26); } while (index > 0); return column; } /// <summary> /// 水平自动递增 例如:从第7行第2列开始增加到100 ("sheet1",7,2,100) /// </summary> /// <param name="ShetName">sheet名称</param> /// <param name="bRow">开始行</param> /// <param name="bColumn">开始列</param> /// <param name="index">增加长度</param> public void AutoHorizontalIndex(string ShetName, int row, int col, int num) { ws = (Excel.Worksheet)wb.Sheets[ShetName]; string colCode = IndexToColumn(col+num-1); string rowCode = IndexToColumn(col); string area = rowCode + row + ":" + colCode + row; object[,] arr = new object[1, num]; for (int i = 0; i < num; i++) { arr[0,i] = i + 1; } Excel.Range range = ws.get_Range(area); range.Value2 = arr; } /// <summary> /// 竖直自动递增 例如:从第7行第2列开始 自动增加到100 (“Sheet1”,7,2,100) /// </summary> /// <param name="ShetName">sheet名称</param> /// <param name="bRow">开始行</param> /// <param name="bColumn">开始列</param> /// <param name="num">增加长度</param> public void AutoVerticalIndex(string ShetName, int row, int col, int num) { ws = (Excel.Worksheet)wb.Sheets[ShetName]; string colCode = IndexToColumn(col); string area = colCode + row + ":" + colCode + (row + num -1); object[,] arr = new object[num,1]; for (int i = 0; i < num; i++) { arr[i, 0] = i + 1; } Excel.Range range = ws.get_Range(area); range.Value2 = arr; } /// <summary> /// 黏贴模板 /// </summary> /// <param name="ShetName">sheet名称</param> /// <param name="area">开始区域 如"A2"</param> /// <param name="area2">结束区域 如 "G42"</param> /// <param name="range">模板</param> public void Paste_Range_Model(string ShetName, string area, string area2, Excel.Range rangeModel) { ws = (Excel.Worksheet)wb.Sheets[ShetName]; Excel.Range range = rangeModel; //黏贴区域 Excel.Range newRange = ws.get_Range(area, area2); range.Copy(); ws.Paste(newRange, missing); } /// <summary> /// 拷贝模板 /// </summary> /// <param name="ShetName">sheet名称</param> /// <param name="area">开始区域 如"A2"</param> /// <param name="area2">结束区域 如 "G42"</param> public Excel.Range Copy_Range_Model(string ShetName, string area, string area2) { ws = (Excel.Worksheet)wb.Sheets[ShetName]; Excel.Range range = ws.get_Range(area, area2); return range; } /// <summary> /// 插入行 /// </summary> /// <param name="ShetName">工作薄的名称</param> /// <param name="rowIndex">从第几行开始索引(第一行是1)</param> /// <param name="count">插入几行</param> public void InsertExcelHeader(string ShetName, int rowIndex, int count) { ws = (Excel.Worksheet)wb.Sheets[ShetName]; Excel.Range range = (Excel.Range)ws.Rows[rowIndex, missing]; for (int i = 0; i < count; i++) { range.Insert(Excel.XlDirection.xlDown); } } /// <summary> /// 合并单元格 /// </summary> /// <param name="ShetName">sheet名称</param> /// <param name="area">区域 例如(A2:G2)</param> public void MergeExcelRange(string ShetName, string area) { ws = (Excel.Worksheet)wb.Sheets[ShetName]; ws.get_Range(area, missing).Merge(0); } /// <summary> /// 显示sheet /// </summary> /// <param name="ShetName">sheet名称</param> public void ShowWorkSheet(string ShetName) { try { ws = (Excel.Worksheet)wb.Sheets[ShetName]; } catch { throw new Exception("不存在该Sheet"); } ws.Visible = Excel.XlSheetVisibility.xlSheetHidden; } /// <summary> /// 隐藏sheet /// </summary> /// <param name="ShetName">sheet名称</param> public void HideWorkSheet(string ShetName) { try { ws = (Excel.Worksheet)wb.Sheets[ShetName]; } catch { throw new Exception("不存在该Sheet"); } ws.Visible = Excel.XlSheetVisibility.xlSheetVeryHidden; } /// <summary> /// 检索值个数 (查询某个工作薄) /// </summary> /// <param name="strValue">查询值</param> /// <param name="sheetIndex">工作薄名称</param> public int SearchValueCount(string strValue, string sheetIndex) { //使用行 int indxRow = ws.UsedRange.Rows.Count; //使用列 int indxCol = ws.UsedRange.Columns.Count; int count = 0; string str = null; for (int i = 1; i < indxRow; i++) { for (int j = 1; j < indxCol; j++) { str = GetRangValue(sheetIndex, i, j); str = str.Trim().ToLower(); strValue = strValue.Trim().ToLower(); if (strValue == str) { count++; } } } return count; } /// <summary> /// 检索值(精确) /// </summary> /// <param name="strValue">查询值</param> /// <param name="sheetIndex">工作薄名称</param> /// <returns></returns> public string SearchValue(string strValue, string sheetIndex) { //使用行 int indxRow = ws.UsedRange.Rows.Count; //使用列 int indxCol = ws.UsedRange.Columns.Count; //存储行和列 Dictionary<int, int> dic = new Dictionary<int, int>(); int count = 0; string str = null; for (int i = 1; i < indxRow; i++) { for (int j = 1; j < indxCol; j++) { str = GetRangValue(sheetIndex, i, j); str = str.Trim().ToLower(); strValue = strValue.Trim().ToLower(); if (strValue == str) { dic.Add(i, j); count++; } } } return ""; } /// <summary> /// 将图片插入到指定的单元格位置。 /// 注意:图片必须是绝对物理路径 /// </summary> /// <param name="RangeName">单元格名称,例如:B4</param> /// <param name="PicturePath">要插入图片的绝对路径。</param> public void InsertPicture(string ShetName, string area, string PicturePath) { ws = (Excel.Worksheet)wb.Sheets[ShetName]; getRange = ws.get_Range(area,missing); getRange.Select(); Excel.Pictures pics = (Excel.Pictures)ws.Pictures(missing); pics.Insert(PicturePath, missing); } /// <summary> /// 将Excel导入到 DataTable /// </summary> /// <param name="filePath">Excel文件路径</param> /// <param name="sheetName">工作薄名称</param> /// <returns></returns> public DataTable ExcelToDataTable(string filePath, string sheetName) { OleDbDataAdapter oda = new OleDbDataAdapter(); OleDbConnection oleCon = new OleDbConnection(); string strCon = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=@filePath;Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"; strCon = strCon.Replace("@filePath", filePath); DataTable dt = new DataTable(); oleCon.ConnectionString = strCon; oleCon.Open(); DataTable table = oleCon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); //string sheetName = table.Rows[0][2].ToString(); string sql = "select * from [@sheetName$]"; sql = sql.Replace("@sheetName", sheetName); oda = new System.Data.OleDb.OleDbDataAdapter(sql, oleCon); oda.Fill(dt); oleCon.Close(); return dt; } #endregion #region Excel样式 /// <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 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 } /// <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 ExcelHAlign { 常规 = 1, 靠左, 居中, 靠右, 填充, 两端对齐, 跨列居中, 分散对齐 } /// <summary> /// 自动调整行高 /// </summary> /// <param name="columnNum">行号</param> public void RowAutoFit(int rowNum) { //获取当前正在使用的工作表 Excel.Worksheet worksheet = (Excel.Worksheet)ExApp.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)ExApp.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 = IndexToColumn(startColumn); string strEndColumn = IndexToColumn(endColumn); //获取当前正在使用的工作表 Excel.Worksheet worksheet = (Excel.Worksheet)ExApp.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)ExApp.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 = IndexToColumn(columnNum); //获取当前正在使用的工作表 Excel.Worksheet worksheet = (Excel.Worksheet)ExApp.ActiveSheet; Excel.Range range = (Excel.Range)worksheet.Columns[strcolumnNum + ":" + strcolumnNum, System.Type.Missing]; range.EntireColumn.AutoFit(); } /// <summary> /// 字体颜色 /// </summary> /// <param name="indexRow">开始单元格 例如 A1</param> /// <param name="indexCol">结束单元格 例如 C5</param> /// <param name="color">颜色索引</param> public void FontColor(string indexRow, string indexCol, ColorIndex color) { Excel.Range range = ExApp.get_Range(indexRow, indexCol); range.Font.ColorIndex = color; } /// <summary> /// 字体样式(加粗,斜体,下划线) /// </summary> /// <param name="indexRow">开始单元格 例如 A1</param> /// <param name="indexCol">结束单元格 例如 C5</param> /// <param name="isBold">是否加粗</param> /// <param name="isItalic">是否斜体</param> /// <param name="underline">下划线类型</param> public void FontStyle(string indexRow, string indexCol, bool isBold, bool isItalic, UnderlineStyle underline) { Excel.Range range = ExApp.get_Range(indexRow, indexCol); range.Font.Bold = isBold; range.Font.Underline = underline; range.Font.Italic = isItalic; } /// <summary> /// 单元格字体及大小 /// </summary> /// <param name="indexRow">开始单元格 例如 A1</param> /// <param name="indexCol">结束单元格 例如 C5</param> /// <param name="fontName">字体名称</param> /// <param name="fontSize">字体大小</param> public void FontNameSize(string indexRow, string indexCol, string fontName, int fontSize) { Excel.Range range = ExApp.get_Range(indexRow, indexCol); range.Font.Name = fontName; range.Font.Size = fontSize; } /// <summary> /// 单元格背景色及填充方式 /// </summary> /// <param name="indexRow">开始单元格 例如 A1</param> /// <param name="indexCol">结束单元格 例如 C5</param> /// <param name="color">颜色</param> public void CellsBackColor(string indexRow, string indexCol, ColorIndex color) { Excel.Range range = ExApp.get_Range(indexRow, indexCol); range.Interior.ColorIndex = color; range.Interior.Pattern = Pattern.Solid; } /// <summary> /// 单元格背景色及填充方式 /// </summary> /// <param name="indexRow">开始单元格 例如 A1</param> /// <param name="indexCol">结束单元格 例如 C5</param> /// <param name="color">颜色</param> /// <param name="pattern">图案样品</param> public void CellsBackColor(string indexRow, string indexCol, ColorIndex color, Pattern pattern) { Excel.Range range = ExApp.get_Range(indexRow, indexCol); 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)ExApp.ActiveSheet; Excel.Range range = (Excel.Range)worksheet.Rows[startRow.ToString() + ":" + endRow.ToString(), System.Type.Missing]; range.RowHeight = height; } #endregion /// <summary> /// 另存文件 /// </summary> public void SaveAs() { wb.SaveAs(this.outputPath, missing, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing); } /// <summary> /// 保存 /// </summary> public void Save() { wb.Save(); } #region 注销 /// <summary> /// 结束Excel进程 /// </summary> public void KillExcelProcess() { Process[] arrProcess = Process.GetProcessesByName("Excel"); DateTime startTime; foreach (Process p in arrProcess) { startTime = p.StartTime; if (startTime > beforeTime && startTime < afterTime) p.Kill(); } } /// <summary> /// 注销 /// </summary> public void Dispose() { if (ExApp != null) { ExApp.Workbooks.Close(); ExApp.Quit(); KillExcelProcess(); GC.Collect(); } } //[DllImport("User32.dll", CharSet = CharSet.Auto)] //public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID); //public void Dispose(bool bl) //{ // ExApp.Workbooks.Close(); // ExApp.Quit(); // if (ExApp != null) // { // IntPtr t = new IntPtr(ExApp.Hwnd); //得到这个句柄,具体作用是得到这块内存入口 // int k = 0; // GetWindowThreadProcessId(t, out k); //得到本进程唯一标志k // System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k); //得到对进程k的引用 // p.Kill(); //关闭进程k // } // GC.Collect(); //} #endregion } }