C#中创建、打开、读取、写入、保存Excel的一般性代码 首先,在引用的COM中找到Microsoft Excel 11.0 Object Library,添加。 using System;
xApp.Visible=true;
Missing.Value,Missing.Value,Missing.Value,Missing.Value, Missing.Value,Missing.Value,Missing.Value,Missing.Value); //xBook=xApp.Workbooks.Add(Missing.Value);//新建文件的代码
Excel.WorksheetxSheet=(Excel.Worksheet)xBook.Sheets[1]; //读取数据,通过Range对象 //读取,通过Range对象,但使用不同的接口得到Range //写入数据 //保存方式一:保存WorkBook //保存方式二:保存WorkSheet //保存方式三
C#如何向EXCEL写入数据 我按着微软技术支持网上的方法写入数据:使用“自动化”功能逐单元格传输数据,代码如下: // Add data to cells in the first worksheet in the newworkbook. // Apply bold to cells A1:B1. // Save the Workbook and quit Excel.
using System; using System.IO; using System.Web; using System.Web.SessionState; using NickLee.Common.ExcelLite; namespace excel1 { /// <summary> /// excel 的摘要说明。 /// </summary> public class excel { public excel() { // // TODO: 在此处添加构造函数逻辑 fileName = HttpContext.Current.Server.MapPath(".")+"\\temp\\"+g+".xls"; } private Guid g= Guid.NewGuid(); private stringfileName; private ExcelFile ec =newExcelFile(); ///<summary> /// 从model中复制模版到temp中 /// </summary> /// <param name="modelName">只需传入模版的名字即可(注意是字符串)</param> public void copyModel(stringmodelName) { string MName = HttpContext. Current.Server.MapPath(".")+"\\model\\"+modelName; File.Copy(MName,fileName); } /// <summary> /// 设置EXCEL表中的字表个数,字表在这个表中统一命名为“续表”+数字序号 /// </summary> /// <paramname="sheetnum">设置字表的个数</param> public void setSheets(int sheetnum) { ec.LoadXls(fileName); ExcelWorksheet wsx=ec.Worksheets[0]; for (inty=0;y<sheetnum;y++) { int num = y+1; ec.Worksheets.AddCopy("续表"+num,wsx); } } ///<summary> /// 给EXCEL表的各个字段设置值 ///</summary> /// <param name="sheetnum">表的序号,注意表是以“0”开始的</param> /// <param name="x">对应于EXCEL的最左边的数字列</param> /// <param name="y">对应于EXCEL的最上面的字母列</param> /// <param name="values">需要写入的值</param> public void setValues(int sheetnum,int x,int y,stringvalues) { ec.Worksheets[sheetnum].Cells[x,y].Value=values;; } ///<summary> /// 保存函数,要是文件中有相同的文件就要删除了, ///然后重新写入相同文件名的新EXCEL表 /// </summary> public voidsaveFile() { if(File.Exists(fileName)) { File.Delete(fileName); ec.SaveXls(fileName); } else { ec.SaveXls(fileName); } } /// <summary> /// 显示的EXCEL表格 /// </summary> public voidshowFile() { HttpContext.Current.Response.Charset =System.Text.Encoding.Default.WebName; HttpContext.Current.Response.ContentType ="application/vnd.ms-excel"; HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.UTF8; HttpContext.Current.Response.WriteFile(fileName); HttpContext.Current.Response.End(); } } } 小结一些C#读写Excel文件的相关技巧,毕竟Excel打印更为方便和实用,一个是Excel打印输出编码比Word文件打印数据简单些,另一个是Excel本身对数据超强计算处理功能;赶巧最近项目又涉及Excel报表统计打印的问题,所以在把其中的一些技术记录下来与大家一起分析讨论,次篇主要涉及两个方面内容: 1、读写Excel文件 A、设计Excel模版 B、打开一个目标文件并且读取模版内容 C、目标文件按格式写入需要的数据 D、保存并且输出目标Excel文件 2、 Excel对象资源释放,这个在以前项目没有注意彻底释放使用到Excel对象,对客户计算机资源造成一定浪费,此次得到彻底解决。 下面是一个Excel打印输出的Demo 1、创建一个叫DemoExcel的项目 2、引用COM,包括:Microsoft.Excel.x.0.Object.Library,Microsoft.Office.x.0.Object.Library建议安装正版OFFICE,而且版本在11.0以上(Office2003以上),引用以上两个Com后,在项目引用栏发现多了Excel、Microsoft.Office.Core,VBIDE三个 Library. 3、下面建立一些模拟的数据,此处为街镇信息 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using Microsoft.Office.Interop.Excel; using Microsoft.Office.Core; using System.IO; using System.Reflection;
namespace DemoExcel{ public partial class Form1 : Form {
private object missing =Missing.Value; private Microsoft.Office.Interop.Excel.Application ExcelRS; private Microsoft.Office.Interop.Excel.Workbook RSbook; private Microsoft.Office.Interop.Excel.Worksheet RSsheet;
public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgse) { // TODO: 这行代码将数据加载到表“dataSet1.STREET”中。您可以根据需要移动或移除它。 this.sTREETTableAdapter.Fill(this.dataSet1.STREET); } private void button1_Click(object sender, EventArgse) { string OutFilePath =System.Windows.Forms.Application.StartupPath + @"emp.xls"; string TemplateFilePath =System.Windows.Forms.Application.StartupPath + @"模版.xls"; PrintInit(TemplateFilePath,OutFilePath); } //Excle输出前初始化 ///<summary> /// ///</summary> ///<returns></returns> public bool PrintInit(string templetFile, stringoutputFile) { Try { if (templetFile == null) { MessageBox.Show("Excel模板文件路径不能为空!"); return false; } if (outputFile == null) { MessageBox.Show("输出Excel文件路径不能为空!"); return false; } //把模版文件templetFile拷贝到目输出文件outputFile中,并且目标文件可以改写 System.IO.File.Copy(templetFile, outputFile, true); if (this.ExcelRS != null) ExcelRS = null; //实例化ExcelRS对象 ExcelRS = new Microsoft.Office.Interop.Excel.ApplicationClass(); //打开目标文件outputFile RSbook = ExcelRS.Workbooks.Open(outputFile, missing, missing, missing, missing,missing, missing, missing, missing, missing, missing, missing, missing, missing,missing); //设置第一个工作溥 RSsheet = (Microsoft.Office.Interop.Excel.Worksheet)RSbook.Sheets.get_Item(1);. //激活当前工作溥 RSsheet.Activate(); 在当前工作溥写入内容 for (int i = 0; i < this.dataGridView1.RowCount; i++) { RSsheet.Cells[3 + i, 1] = this.dataGridView1[0, i].Value.ToString(); RSsheet.Cells[3 + i, 2] = this.dataGridView1[1, i].Value.ToString(); RSsheet.Cells[3 + i, 3] = this.dataGridView1[2, i].Value.ToString(); } //保存目标文件 RSbook.Save(); //设置DisplayAlerts ExcelRS.DisplayAlerts = false; ExcelRS.Visible = true; //ExcelRS.DisplayAlerts = true; //释放对象 RSsheet = null; RSbook = null; ExcelRS = null; //释放内存 GcCollect(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); return false; } return true; } public voidGcCollect() { GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } } } 特别说明: a、引用Microsoft.Office.Interop.Excel; using Microsoft.Office.Core; b、(关键)在程序中特别释放Excel资源的时候既要设置对象为null,又要强制回收内存,这样才能彻底回收资源。 c 、引用的 Office 组建版本是个敏感问题,不同版本之间有细微差别,需要分别处理。 |
|