c# 操作Excel

摘要:
=null){FileInfoold=newFileInfo;if{File.Delete;}wb.SaveAs;foreach{ReleaseCOM;}ReleaseCOM;ReleaseCOM;ReleaseCOM;app.Quit();ReleaseCOM;}}//////杀掉进程的方式保存excel。///用来解决正常保存时出现的公式异常问题。

基本操作类

 	public class ExcelUtil
    	{
       
        public void ReleaseCOM(object pObj)//释放资源
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(pObj);
            }
            catch
            {
                throw new Exception("释放资源时发生错误!");
            }
            finally
            {
                pObj = null;
            }
        }
        public ExcelUtil(string filePath)
        {
            this.filePath = filePath;
            app = new Microsoft.Office.Interop.Excel.Application();//打开一个Excel应用
            if (app == null)
            {
                return;
            }
            wbs = app.Workbooks;
            wb = wbs.Add(filePath);
            shs = wb.Sheets;
            int sheetNumber = shs.Count;
            for (int i = 1; i <= sheetNumber; i++)
            {
                _Worksheet sh = (_Worksheet)shs.get_Item(i);
                this.ShList.Add(sh);
            }
        }
        /// <summary>
        /// 保存文件
        /// </summary>
        public ExcelUtil(string filePath, int addSheet)
        {
            this.filePath = filePath;
            app = new Microsoft.Office.Interop.Excel.Application();//打开一个Excel应用
            if (app == null)
            {
                return;
            }
            wbs = app.Workbooks;
            wb = wbs.Add(filePath);
            shs = wb.Sheets;
            int sheetNumber = shs.Count;
            int addSheetCount = addSheet - sheetNumber;
            if (addSheetCount > 0)
            {
                for (int i = 0; i < addSheetCount; i++)
                {
                    var sheet = (_Worksheet)shs.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                }
            }
            int currentSheetNumber = shs.Count;
            for (int i = 1; i <= currentSheetNumber; i++)
            {
                _Worksheet sh = (_Worksheet)shs.get_Item(i);
                this.ShList.Add(sh);
            }
        }
        /// <summary>
        /// 保存文件
        /// </summary>
        public void save()
        {
            if (filePath != null)
            {
                FileInfo old = new FileInfo(filePath);
                if (old.Exists)
                {
                    File.Delete(filePath);
                }
                wb.SaveAs(filePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                foreach (_Worksheet inst in shList)
                {
                    ReleaseCOM(inst);
                }
                ReleaseCOM(shs);
                ReleaseCOM(wb);
                ReleaseCOM(wbs);
                app.Quit();
                ReleaseCOM(app);
            }
        }
        /// <summary>
        /// 杀掉进程的方式保存excel。
        /// 用来解决正常保存时出现的公式异常问题。
        /// </summary>
        public void saveByKillProcess()
        {
            if (filePath != null)
            {
                try
                {
                    FileInfo old = new FileInfo(filePath);
                    if (old.Exists)
                    {
                        File.Delete(filePath);
                    }
                    wb.SaveAs(filePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                    foreach (_Worksheet inst in shList)
                    {
                        ReleaseCOM(inst);
                    }
                    ReleaseCOM(shs);
                    ReleaseCOM(wb);
                    ReleaseCOM(wbs);
                    KillExcel(app);
                }
                catch (System.Exception e)
                {
                    logger.Debug(e.Message);
                }
            }
        }


        /// <summary>
        /// 合并Excel单元格
        /// </summary>
        /// <param name="ws">sheet页</param>
        /// <param name="str">要合并单元格的左上角的单元格列号A</param>
        /// <param name="i">要合并的单元格的左上角的单元格行号2</param>
        /// <param name="str3">要合并单元格的右下角的单元格列号B</param>
        /// <param name="i">要合并的单元格的右下角的单元格行号2</param>
        /// <param name="j">表格最后一行的行号</param>
        /// <returns>单元格</returns>
        public static Range CombineExcel(_Worksheet ws, int colLeft, int rowUp, int colRight, int rowDown)
        {
            try
            {
                string str1 = GetColStrFromInt(colLeft) + rowUp;
                string str2 = GetColStrFromInt(colRight) + rowDown;
                Range range = ws.get_Range(str1, str2);
                range.Merge(0);
                range.HorizontalAlignment = XlHAlign.xlHAlignCenter;
                range.Font.Underline = false;

                range.WrapText = true;
                //  range.EntireColumn.AutoFit();
                range.Borders.LineStyle = 1;
                return range;
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                return null;
            }
        }

        /// <summary>
        /// 传入列号得到对应的列名称,从1开始,1代表第A列
        /// </summary>
        /// <param name="col">列号</param>
        /// <returns></returns>
        public static string GetColStrFromInt(int col)
        {
            col = col + 'A' - 1;
            string colStr = "";
            if (col > (int)'Z')
            {
                colStr = Convert.ToChar((col - 90 - 1) / 26 + 'A').ToString() +
                    Convert.ToChar((col - 90 - 1) % 26 + 'A').ToString();
                return colStr;
            }
            else
                return Convert.ToChar(col).ToString();
        }

        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
        private void KillExcel(Microsoft.Office.Interop.Excel.Application excel)
        {
            IntPtr t = new IntPtr(excel.Hwnd); //得到这个句柄,具体作用是得到这块内存入口
            int k = 0;
            GetWindowThreadProcessId(t, out k); //得到本进程唯一标志k
            System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k); //得到对进程k的引用
            p.Kill(); //关闭进程k
        }
        private Microsoft.Office.Interop.Excel.Application app;
        private Workbooks wbs;
        private _Workbook wb;
        private Sheets shs;
        private List<_Worksheet> shList = new List<_Worksheet>();
        public List<_Worksheet> ShList
        {
            get
            {
                return shList;
            }
            set
            {
                shList = value;
            }
        }
        private string filePath;
        protected readonly static log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    }

得到一个合并range插入数据

 		private Range GetCurrentRange(_Worksheet ws, int colLeft, int rowUp, int colRight, int rowDown, string result)
        {
            Range currentRange = null;
            currentRange = ExcelUtil.CombineExcel(ws, colLeft, rowUp, colRight, rowDown);
            currentRange.Value2 = result;插入结果
            currentRange.Borders.LineStyle = 0;//边框线
			currentRange.Font.ColorIndex = 3;//插入颜色
			currentRange.Font.Bold = true;//加粗
            currentRange.ColumnWidth = 100;//控制列宽
 			currentRange.HorizontalAlignment = XlHAlign.xlHAlignLeft;//文字的位置
            currentRange.Borders[XlBordersIndex.xlEdgeBottom].Weight = XlBorderWeight.xlThick;//下边框加粗
   			var range = ws.Cells;//选中整个文档
            range.Interior.ColorIndex = 2;//填充背景颜色
			return currentRange;
        }

创建超链接

		/// <summary>
        /// Inserts the catalogue.目录超链接
        /// </summary>
        /// <param name="ws">The ws.</param>
        /// <param name="colLeft">The col left.</param>
        /// <param name="rowUp">The row up.</param>
        /// <param name="colRight">The col right.</param>
        /// <param name="rowDown">The row down.</param>
        /// <param name="result">The result.</param>
        /// <param name="colWidth">Width of the col.</param>
        /// <param name="sheet">The sheet.</param>
        private void InsertCatalogue(_Worksheet ws, int colLeft, int rowUp, int colRight, int rowDown, string result, string sheet)
        {
            var currentRange = this.GetCurrentRange(ws, colLeft, rowUp, colRight, rowDown, result);
            currentRange.Font.ColorIndex = 5;
            currentRange.Font.Bold = true;
            string hyperlink = "#" + sheet + "!" + ExcelUtil.GetColStrFromInt(colLeft) + rowUp;
            ws.Hyperlinks.Add(currentRange, hyperlink, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
            currentRange.Font.Underline = false;
            currentRange.HorizontalAlignment = XlHAlign.xlHAlignLeft;
        }

对数据画统计图

  		private void Chart(_Worksheet ws, int startRow, Catalogue catalogue)
        {
            Range chartRange;

            ChartObjects xlCharts = (ChartObjects)ws.ChartObjects(Type.Missing);
            ChartObject myChart = (ChartObject)xlCharts.Add(250, 20, 600, 300);
            Chart chartPage = myChart.Chart;
            string title = "标题名字";
            this.InsertResult(ws, 6, 25, 6, 25, title);
            string lowRange = ws.get_Range("K31", Type.Missing).Value2.ToString();
            string hightRange = ws.get_Range("L31", Type.Missing).Value2.ToString();
            double temp = 0;
            bool isAllLine = false;
            string chartRangeSelect = "I31:I" + startRow + ",K31:K" + startRow + ",L31:L" + startRow;
            if (double.TryParse(lowRange, out temp) && double.TryParse(hightRange, out temp))
            {
                isAllLine = true;
            }
            else
            {
                if (!double.TryParse(lowRange, out temp))
                {
                    chartRangeSelect = "I31:I" + startRow + ",L31:L" + startRow;
                }
                else
                {
                    chartRangeSelect = "I31:I" + startRow + ",K31:K" + startRow;
                }
            }
            chartRange = ws.get_Range(chartRangeSelect, Type.Missing);
            chartPage.ChartWizard(chartRange, XlChartType.xlConeCol, Type.Missing, XlRowCol.xlColumns, Type.Missing, Type.Missing, true, title, Type.Missing, Type.Missing, Type.Missing);

            chartPage.SetSourceData(chartRange, XlRowCol.xlColumns);
            Series oSeries1 = (Series)chartPage.SeriesCollection(2);
            oSeries1.ChartType = XlChartType.xlLine;
            oSeries1.Border.ColorIndex = 3;
            Series oSeries = (Series)chartPage.SeriesCollection(1);
            oSeries.ChartType = XlChartType.xlLine;
            oSeries.Border.ColorIndex = 5;
            if (isAllLine)
            {
                Series oSeries2 = (Series)chartPage.SeriesCollection(3);
                oSeries2.ChartType = XlChartType.xlLine;
                oSeries2.Border.ColorIndex = 3;
            }
            chartPage.Legend.Delete();
            Axis xAxis = (Axis)chartPage.Axes(XlAxisType.xlCategory, XlAxisGroup.xlPrimary);
            xAxis.Delete();
            var range = ws.Cells;
            range.WrapText = false;
        }

免责声明:文章转载自《c# 操作Excel》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇jenkins操作手册以及脚本编写查看SQL server 2008 R2 的Service Package 版本号(同样适用于SQL Server 2005)下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

C# 标签打印示例 1

初次写博客,有哪些不足的地方,还请多多指点,给予建议,谢谢! 如若想要源码,请留言。 本实例是在Webservice 中通过excel做模板来打印标签。具体需求是:一个订单一页纸打印4行分录,如果超过4行,则再次按照原格式换纸打印,如果行数未满4行,则补空行。一、实现步骤: 1、首先在EXCEL 画好模版 (后缀名是 .xlt )2、在程序中调用EX...

js 预览 excel,js-xlsx的使用

js-xlsx 介绍 由SheetJS出品的js-xlsx是一款非常方便的只需要纯JS即可读取和导出excel的工具库,功能强大,支持格式众多,支持xls、xlsx、ods(一种OpenOffice专有表格文件格式)等十几种格式。本文全部都是以xlsx格式为例。 官方github:https://github.com/SheetJS/js-xlsx 本...

layui 学习笔记(四) 复杂表头前台Excel导出

layui - excel 复杂表头导出- 第三方插件实现 参考:https://fly.layui.com/extend/excel/演示:http://excel.wj2015.com/    http://excel.wj2015.com/_book/docs/%E5%87%BD%E6%95%B0%E5%88%97%E8%A1%A8/%E5%AF%B...

第07组(69) 需求分析报告

1.团队基本情况 1.1团队项目整体计划安排 项目分工表 工种 组员 任务 统筹 陈晟新 考察任务进度,负责人员调度,后端研究 美工 李佳乐 UI设计,原型设计,细化用户需求 测试 孙晴晴 测试方案制定,评测测试系统 服务器 吴洁颖 研究服务器方面的需求 网页 陈小楚,何文龙 网页的制作,交互的实现 算法 傅智鑫,王璐 酷转的...

C/C++读写excel文件 的几种方式

因为有些朋友问代码的问题,将OLE读写的代码分享在这个地方,大家请自己看。http://blog.csdn.net/fullsail/article/details/8449448 C++读取Excel的XLS文件的方法有很多,但是也许就是因为方法太多,大家在选择的时候会很疑惑。由于前两天要做导表工具,比较了常用的方法,总结一下写个短文, 1.OL...

用python读取带密码的excel文件中的数据

用python读取带密码的excel文件中的数据,程序代码如下: #filename:readingxls.py ''' 此程序的作用为:用python读取带密码的excel文件中的数据。 首先通过pip安装xlrd第三方库 pip3 install xlrd 请输入excel文件路径:D:x1.xls ''' import xlrd path=input...