C#中创建、打开、读取、写入、保存Excel的一般性代码
首先,在引用的COM中找到Microsoft Excel 11.0 Object Library,添加。
using System;
using System.Reflection; // 引用这个才能使用Missing字段
using Excel;
namespace CExcel1
{
class Class1
{
[STAThread]
static voidMain(string[] args)
{
//创建Application对象
Excel.ApplicationxApp=new Excel.ApplicationClass();
xApp.Visible=true;
//得到WorkBook对象,可以用两种方式之一:下面的是打开已有的文件
Excel.Workbook xBook=xApp.Workbooks._Open(@"D:\Sample.xls",
Missing.Value,Missing.Value,Missing.Value,Missing.Value,
Missing.Value,Missing.Value,Missing.Value,Missing.Value,
Missing.Value,Missing.Value,Missing.Value,Missing.Value);
//xBook=xApp.Workbooks.Add(Missing.Value);//新建文件的代码
//指定要操作的Sheet,两种方式:
Excel.WorksheetxSheet=(Excel.Worksheet)xBook.Sheets[1];
//Excel.WorksheetxSheet=(Excel.Worksheet)xApp.ActiveSheet;
//读取数据,通过Range对象
Excel.Rangerng1=xSheet.get_Range("A1",Type.Missing);
Console.WriteLine(rng1.Value2);
//读取,通过Range对象,但使用不同的接口得到Range
Excel.Rangerng2=(Excel.Range)xSheet.Cells[3,1];
Console.WriteLine(rng2.Value2);
//写入数据
Excel.Rangerng3=xSheet.get_Range("C6",Missing.Value);
rng3.Value2="Hello";
rng3.Interior.ColorIndex=6;//设置Range的背景色
//保存方式一:保存WorkBook
xBook.SaveAs(@"D:\CData.xls",
Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Excel.XlSaveAsAccessMode.xlNoChange,Missing.Value,Missing.Value,Missing.Value,
Missing.Value,Missing.Value);
//保存方式二:保存WorkSheet
xSheet.SaveAs(@"D:\CData2.xls",
Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value);
//保存方式三
xBook.Save();
xSheet=null;
xBook=null;
xApp.Quit(); //这一句是非常重要的,否则Excel对象不能从内存中退出
xApp=null;
}
}
}
C#如何向EXCEL写入数据
我按着微软技术支持网上的方法写入数据:使用“自动化”功能逐单元格传输数据,代码如下:
// Start a new workbook in Excel.
m_objExcel = new Excel.Application();
m_objBooks = (Excel.Workbooks)m_objExcel.Workbooks;
m_objBook = (Excel._Workbook)(m_objBooks.Add(m_objOpt));
// Add data to cells in the first worksheet in the newworkbook.
m_objSheets = (Excel.Sheets)m_objBook.Worksheets;
m_objSheet = (Excel._Worksheet)(m_objSheets.get_Item(1));
m_objRange = m_objSheet.get_Range("A1", m_objOpt);
m_objRange.Value = "Last Name";
m_objRange = m_objSheet.get_Range("B1", m_objOpt);
m_objRange.Value = "First Name";
m_objRange = m_objSheet.get_Range("A2", m_objOpt);
m_objRange.Value = "Doe";
m_objRange = m_objSheet.get_Range("B2", m_objOpt);
m_objRange.Value = "John";
// Apply bold to cells A1:B1.
m_objRange = m_objSheet.get_Range("A1", "B1");
m_objFont = m_objRange.Font;
m_objFont.Bold=true;
// Save the Workbook and quit Excel.
m_objBook.SaveAs(m_strSampleFolder + "Book1.xls", m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, Excel.XlSaveAsAccessMode.xlNoChange, m_objOpt, m_objOpt, m_objOpt, m_objOpt);
m_objBook.Close(false, m_objOpt, m_objOpt);
m_objExcel.Quit();
EXCEL表用c#来读
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 组建版本是个敏感问题,不同版本之间有细微差别,需要分别处理。