初学c#,由于项目需要操作Excel。网上搜索了一番,资料挺多。不过写的过于冗余,一上来就是一大断代码,看的头疼,
总结了下,不足的忘补充
考虑到兼容问题,针对office2003的操作
---必须的库 Microsoft.Office.Interop.Excel.dll (附件)
----代码中用到的类
- using System;
- using System.Drawing;
- using System.Collections;
- using System.ComponentModel;
- using System.Data;
- using System.IO;
- using System.Text;
- using System.Windows;
- using System.Reflection;
- using System.Runtime.InteropServices;
- using Excel = Microsoft.Office.Interop.Excel;
创建一个新的Excel文件
(代码片段1)
- Object missing = Missing.Value;
- Excel.Application m_objExcel = new Excel.Application();
- Excel.Workbooks m_objWorkBooks = m_objExcel.Workbooks;
- Excel.Workbook m_objWorkBook = m_objWorkBooks.Add(true);
- Excel.Sheets m_objWorkSheets = m_objWorkBook.Sheets; ;
- Excel.Worksheet m_objWorkSheet = (Excel.Worksheet)m_objWorkSheets[1];
- try
- {
- m_objExcel.Save("f:129.xls");
- }
- catch (Exception e)
- {
- }
- finally {
- m_objWorkBooks.Close();
- m_objExcel.Quit();
- }
------ 操作单元格 单元格以横坐标和纵坐标进行导航
在代码一try{}catch(){}之前加入以下代码
(代码片段2)
- m_objExcel.Cells[1, 1] = "建筑节能评估计算报告书";//第一行第一列文赋值
------合并单元格(在代码一try{}catch(){}之前加入以下代码)
- m_objExcel.Cells[1, 1] = "建筑节能评估计算报告书";
- Excel.Range range = m_objExcel.get_Range(m_objExcel.Cells[1, 1], m_objExcel.Cells[1, 10]);
- range.Merge(Type.Missing);//合并单元格
---操作字体大小,颜色,单元格背景色。边框颜色等(在代码一try{}catch(){}之前加入以下代码)
- m_objExcel.Cells[1, 1] = "建筑节能评估计算报告书";
- Excel.Range range = m_objExcel.get_Range(m_objExcel.Cells[1, 1], m_objExcel.Cells[1, 10]);
- range.Merge(Type.Missing);//合并单元格
- range.Font.Size = 25;//字号
- range.HorizontalAlignment = Excel.Constants.xlCenter; //居中对齐
- range.Font.Bold = 17;//字体大小
- // range.Borders.LineStyle = Excel.XlLineStyle.xlContinuous;//边框
- // range.Borders.Color = ColorTranslator.ToOle(Color.Red);//边框颜色
- //range.Interior.ColorIndex = 34;背景色