asp教程.net c# 操作excel详解
system.data;
using system.drawing;
using system.text;
using system.windows.forms;
using microsoft.office.interop.excel;
using system.data.sqlclient;
using system.data.oledb;
using system.reflection;
namespace excelprj
{
///
/// excel 系统中的主文件excel.exe 本身就是 com 组件,通过在.net 项目中引用exel.exe 文件可以实现对excel 的功能控制
/// 与com 组件相互操作是通过使用"包装类"(wrapper class) 和"代理"(proxy) 的机制实现的.包装类使.net 程序可以识别com 组件提供的接口,而代理类则是提供对 com 接口的访问
///
public partial class form1 : form
{
public form1()
{
initializecomponent();
}
private void button3_click(object sender, eventargs e)
{
exporttasks(bind(), datagridview1);
}
//如果 excel 安装在计算机上,侧导出表格内容到 excel
public void exporttasks(dataset tasksdata, datagridview tasksgridview)
{
// 定义要使用的excel 组件接口
// 定义application 对象,此对象表示整个excel 程序
microsoft.office.interop.excel.application excelapp = null ;
// 定义workbook对象,此对象代表工作薄
microsoft.office.interop.excel.workbook workbook;
// 定义worksheet 对象,此对象表示execel 中的一张工作表
microsoft.office.interop.excel.worksheet ws=null;
//定义range对象,此对象代表单元格区域
microsoft.office.interop.excel.range r;
int row = 1; int cell = 1;
try
{
//初始化 application 对象 excelapp
excelapp = new microsoft.office.interop.excel.application();
//在工作薄的第一个工作表上创建任务列表
workbook = excelapp.workbooks.add(xlwbatemplate.xlwbatworksheet);
ws =(worksheet)workbook.worksheets[1];
// 命名工作表的名称为 "task management"
ws.name = "task management";
#region 创建表格的列头
// 遍历数据表中的所有列
foreach (datagridviewcolumn cs in tasksgridview.columns)
{
// 假如并不想把主键也显示出来
if (cs.headertext != "编号")
{
ws.cells[row, cell] = cs.headertext;
r = (range)ws.cells[row, cell];
ws.get_range(r, r).horizontalalignment = microsoft.office.interop.excel.xlvalign.xlvaligncenter;
//此处用来设置列的样式
cell++;
}
}
// 创建行,把数据视图记录输出到对应的excel 单元格
for (int i = 2; i < tasksdata.tables[0].rows.count; i++)
{
for (int j = 1; j < tasksdata.tables[0].columns.count; j++)
{
ws.cells[i, j] = tasksdata.tables[0].rows[i][j].tostring();
// r = (range)ws.cells[i,j];
range rg = (range)ws.get_range(ws.cells[i, j], ws.cells[i, j]);
rg.entirecolumn.column;
// rg.columns.autofit();
rg.numberformatlocal = "@";
}
}
#endregion
}
catch (exception ex)
{
messagebox.show(ex.tostring());
}
//显示 excel
excelapp.visible = true;
}
private void button5_click(object sender, eventargs e)
{
dataset ds = bind();
datagridview1.datasource = ds.tables[0];
}
private dataset bind()
{
sqlconnection conn = new sqlconnection("server=.;database=testmanage;integrated security=sspi");
sqldataadapter da = new sqldataadapter("select fnumber,fexamnum,fname,fsex,fjobadd,fcardid,fbirdate from stuinfo", conn);
dataset ds = new dataset();
da.fill(ds);
return ds;
}
private void button2_click(object sender, eventargs e)
{
savefiledialog sfd = new savefiledialog();
sfd.title = "请选择将导出的excel文件存放路径";
sfd.filename = system.datetime.now.toshortdatestring() + "-学生信息";
sfd.filter = "excel文档(*.xls)|*.xls";
sfd.showdialog();
if (sfd.filename != "")
{
microsoft.office.interop.excel.application excelapp = new microsoft.office.interop.excel.application();
if (excelapp == null)
{
messagebox.show("无法创建excel对象,可能您的机器未安装excel");
}
else
{
microsoft.office.interop.excel.workbooks workbooks = excelapp.workbooks;
microsoft.office.interop.excel.workbook workbook = workbooks.add(xlwbatemplate.xlwbatworksheet);
microsoft.office.interop.excel.worksheet worksheet =(worksheet) workbook.worksheets[1];
dataset ds=bind();
for (int i = 1; i < ds.tables[0].rows.count; i++)
{
for (int j = 1; j < ds.tables[0].columns.count;j++ )
{
if (i == 1)
{
worksheet.cells[i, j] = datagridview1.columns[j].headertext;
}
worksheet.cells[i+1, j] = ds.tables[0].rows[i][j].tostring();
}
}
//保存方式一:保存workbook
//workbook.saveas(@"f:cdata.xls",
// missing.value,missing.value,missing.value,missing.value,missing.value,
// microsoft.office.interop.excel.xlsaveasaccessmode.xlnochange,missing.value,missing.value,missing.value,
// missing.value,missing.value);
//保存方式二:保存worksheet
// worksheet.saveas(@"f:cdata2.xls",
// missing.value, missing.value, missing.value, missing.value,
// missing.value, missing.value, missing.value, missing.value, missing.value);
////保存方式三
//workbook.saved = true;
//workbook.savecopyas(sfd.filename);
system.runtime.interops教程ervices.marshal.releasecomobject(worksheet);
worksheet = null;
system.runtime.interopservices.marshal.releasecomobject(workbook);
workbook = null;
workbooks.close();
system.runtime.interopservices.marshal.releasecomobject(workbooks);
workbooks = null;
excelapp.quit();
system.runtime.interopservices.marshal.releasecomobject(excelapp);
excelapp = null;
messagebox.show("导出excel完成!");
}
}
}
private void button4_click(object sender, eventargs e)
{
string strexcelfilename = @"f:2007-07-16-学生信息.xls";
string strsheetname = "sheet1";
#region aspnet 操作excel 正确
////源的定义
//string strconn = "provider=microsoft.jet.oledb.4.0;data source = " + strexcelfilename + ";extended properties ='excel 8.0;hdr=no;imex=1'";
////sql语句
//string strexcel = "select * from [" + strsheetname + "$]";
////定义存放的数据表
//dataset ds = new dataset();
////连接数据源
//oledbconnection conn = new oledbconnection(strconn);
//conn.open();
////适配到数据源
//oledbdataadapter adapter = new oledbdataadapter(strexcel, conn);
//adapter.fill(ds,"res");
//conn.close();
//// 一般的情况下. excel 表格的第一行是列名
//datagridview2.datasource = ds.tables["res"];
#endregion
#region com 组件读取复杂excel
microsoft.office.interop.excel.application excelapp = null;
microsoft.office.interop.excel.workbook workbook;
microsoft.office.interop.excel.worksheet ws = null;
try
{
excelapp = new microsoft.office.interop.excel.application();
workbook = excelapp.workbooks.open(@"f:book1.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, missing.value, missing.value);
ws = (worksheet)workbook.worksheets[1];
//excel 默认为 256 列..
messagebox.show(ws.cells.columns.count.tostring());
excelapp.quit();
}
catch (exception ex)
{
throw ex;
}
#endregion
}
}
}
一些excel操作详解
一) 使用动态创建的方法
首先创建 excel 对象,使用comobj:
var excelapp: variant;
excelapp := createoleobject( 'excel.application ' );
1) 显示当前窗口:
excelapp.visible := true;
2) 更改 excel 标题栏:
excelapp.caption := '应用程序调用 microsoft excel ';
3) 添加新工作簿:
excelapp.workbooks.add;
4) 打开已存在的工作簿:
excelapp.workbooks.open( 'c:exceldemo.xls ' );
5) 设置第2个工作表为活动工作表:
excelapp.worksheets[2].activate;
或
excelapp.workssheets[ 'sheet2 ' ].activate;
6) 给单元格赋值:
excelapp.cells[1,4].value := '第一行第四列 ';
7) 设置指定列的宽度(单位:字符个数),以第一列为例:
excelapp.activesheet.columns[1].columnswidth := 5;
8) 设置指定行的高度(单位:磅)(1磅=0.035厘米),以第二行为例:
excelapp.activesheet.rows[2].rowheight := 1/0.035; // 1厘米
9) 在第8行之前插入分页符:
excelapp.worksheets[1].rows[8].pagebreak := 1;
10) 在第8列之前删除分页符:
excelapp.activesheet.columns[4].pagebreak := 0;
11) 指定边框线宽度:
excelapp.activesheet.range[ 'b3:d4 ' ].borders[2].weight := 3;
1-左 2-右 3-顶 4-底 5-斜( ) 6-斜( / )
12) 清除第一行第四列单元格公式:
excelapp.activesheet.cells[1,4].clearcontents;
13) 设置第一行字体属性:
excelapp.activesheet.rows[1].font.name := '隶书 ';
excelapp.activesheet.rows[1].font.color := clblue;
excelapp.activesheet.rows[1].font.bold := true;
excelapp.activesheet.rows[1].font.underline := true;
14) 进行页面设置:
a.页眉:
excelapp.activesheet.pagesetup.centerheader := '报表演示 ';
b.页脚:
excelapp.activesheet.pagesetup.centerfooter := '第&p页 ';
c.页眉到顶端边距2cm:
excelapp.activesheet.pagesetup.headermargin := 2/0.035;
d.页脚到底端边距3cm:
excelapp.activesheet.pagesetup.headermargin := 3/0.035;
e.顶边距2cm:
excelapp.activesheet.pagesetup.topmargin := 2/0.035;
f.底边距2cm:
excelapp.activesheet.pagesetup.bottommargin := 2/0.035;
g.左边距2cm:
excelapp.activesheet.pagesetup.leftmargin := 2/0.035;
h.右边距2cm:
excelapp.activesheet.pagesetup.rightmargin := 2/0.035;
i.页面水平居中:
excelapp.activesheet.pagesetup.centerhorizontally := 2/0.035;
j.页面垂直居中:
excelapp.activesheet.pagesetup.centervertically := 2/0.035;
k.打印单元格网线:
excelapp.activesheet.pagesetup.printgridlines := true;
15) 拷贝操作:
a.拷贝整个工作表:
excelapp.activesheet.used.range.copy;
b.拷贝指定区域:
excelapp.activesheet.range[ 'a1:e2 ' ].copy;
c.从a1位置开始粘贴:
excelapp.activesheet.range.[ 'a1 ' ].pastespecial;
d.从文件尾部开始粘贴:
excelapp.activesheet.range.pastespecial;
16) 插入一行或一列:
a. excelapp.activesheet.rows[2].insert;
b. excelapp.activesheet.columns[1].insert;
17) 删除一行或一列:
a. excelapp.activesheet.rows[2].delete;
b. excelapp.activesheet.columns[1].delete;
18) 打印预览工作表:
excelapp.activesheet.printpreview;
19) 打印输出工作表:
excelapp.activesheet.printout;
20) 工作表保存:
if not excelapp.activeworkbook.saved then
excelapp.activesheet.printpreview;
21) 工作表另存为:
excelapp.saveas( 'c:exceldemo1.xls ' );
22) 放弃存盘:
excelapp.activeworkbook.saved := true;
23) 关闭工作簿:
excelapp.workbooks.close;
24) 退出 excel:
excelapp.quit;
(二) 使用delphi 控件方法
在form中分别放入excelapplication, excelworkbook和excelworksheet。
1) 打开excel
excelapplication1.connect;
2) 显示当前窗口:
excelapplication1.visible[0]:=true;
3) 更改 excel 标题栏:
excelapplication1.caption := '应用程序调用 microsoft excel ';
4) 添加新工作簿:
excelworkbook1.connectto(excelapplication1.workbooks.add(emptyparam,0));
5) 添加新工作表:
var temp_worksheet: _worksheet;
begin
temp_worksheet:=excelworkbook1.
worksheets.add(emptyparam,emptyparam,emptyparam,emptyparam,0) as _worksheet;
excelworksheet1.connectto(temp_worksheet);
end;
6) 打开已存在的工作簿:
excelapplication1.workbooks.open (c:a.xls
emptyparam,emptyparam,emptyparam,emptyparam,
emptyparam,emptyparam,emptyparam,emptyparam,
emptyparam,emptyparam,emptyparam,emptyparam,0)
7) 设置第2个工作表为活动工作表:
excelapplication1.worksheets[2].activate; 或
excelapplication1.workssheets[ 'sheet2 ' ].activate;
8) 给单元格赋值:
excelapplication1.cells[1,4].value := '第一行第四列 ';
9) 设置指定列的宽度(单位:字符个数),以第一列为例:
excelapplication1.activesheet.columns[1].columnswidth := 5;
10) 设置指定行的高度(单位:磅)(1磅=0.035厘米),以第二行为例:
excelapplication1.activesheet.rows[2].rowheight := 1/0.035; // 1厘米
11) 在第8行之前插入分页符:
excelapplication1.worksheets[1].rows[8].pagebreak := 1;
12) 在第8列之前删除分页符:
excelapplication1.activesheet.columns[4].pagebreak := 0;
13) 指定边框线宽度:
excelapplication1.activesheet.range[ 'b3:d4 ' ].borders[2].weight := 3;
1-左 2-右 3-顶 4-底 5-斜( ) 6-斜( / )
14) 清除第一行第四列单元格公式:
excelapplication1.activesheet.cells[1,4].clearcontents;
15) 设置第一行字体属性:
excelapplication1.activesheet.rows[1].font.name := '隶书 ';
excelapplication1.activesheet.rows[1].font.color := clblue;
excelapplication1.activesheet.rows[1].font.bold := true;
excelapplication1.activesheet.rows[1].font.underline := true;
16) 进行页面设置:
a.页眉:
excelapplication1.activesheet.pagesetup.centerheader := '报表演示 ';
b.页脚:
excelapplication1.activesheet.pagesetup.centerfooter := '第&p页 ';
c.页眉到顶端边距2cm:
excelapplication1.activesheet.pagesetup.headermargin := 2/0.035;
d.页脚到底端边距3cm:
excelapplication1.activesheet.pagesetup.headermargin := 3/0.035;
e.顶边距2cm:
excelapplication1.activesheet.pagesetup.topmargin := 2/0.035;
f.底边距2cm:
excelapplication1.activesheet.pagesetup.bottommargin := 2/0.035;
g.左边距2cm:
excelapplication1.activesheet.pagesetup.leftmargin := 2/0.035;
h.右边距2cm:
excelapplication1.activesheet.pagesetup.rightmargin := 2/0.035;
i.页面水平居中:
excelapplication1.activesheet.pagesetup.centerhorizontally := 2/0.035;
j.页面垂直居中:
excelapplication1.activesheet.pagesetup.centervertically := 2/0.035;
k.打印单元格网线:
excelapplication1.activesheet.pagesetup.printgridlines := true;
17) 拷贝操作:
a.拷贝整个工作表:
excelapplication1.activesheet.used.range.copy;
b.拷贝指定区域:
excelapplication1.activesheet.range[ 'a1:e2 ' ].copy;
c.从a1位置开始粘贴:
excelapplication1.activesheet.range.[ 'a1 ' ].pastespecial;
d.从文件尾部开始粘贴:
excelapplication1.activesheet.range.pastespecial;
18) 插入一行或一列:
a. excelapplication1.activesheet.rows[2].insert;
b. excelapplication1.activesheet.columns[1].insert;
19) 删除一行或一列:
a. excelapplication1.activesheet.rows[2].delete;
b. excelapplication1.activesheet.columns[1].delete;
20) 打印预览工作表:
excelapplication1.activesheet.printpreview;
21) 打印输出工作表:
excelapplication1.activesheet.printout;
22) 工作表保存:
if not excelapplication1.activeworkbook.saved then
excelapplication1.activesheet.printpreview;
23) 工作表另存为:
excelapplication1.saveas( 'c:exceldemo1.xls ' );
24) 放弃存盘:
excelapplication1.activeworkbook.saved := true;
25) 关闭工作簿:
excelapplication1.workbooks.close;
26) 退出 excel:
excelapplication1.quit;
excelapplication1.disconnect;
(三) 使用delphi 控制excle二维图
在form中分别放入excelapplication, excelworkbook和excelworksheet
var asheet1,achart, range:variant;
1)选择当第一个工作薄第一个工作表
asheet1:=excelapplication1.workbooks[1].worksheets[1];
2)增加一个二维图
achart:=asheet1.chartobjects.add(100,100,200,200);
3)选择二维图的形态
achart.chart.charttype:=4;
4)给二维图赋值
series:=achart.chart.seriescollection;
range:=sheet1!r2c3:r3c9;
series.add(range,true);
5)加上二维图的标题
achart.chart.hastitle:=true;
achart.chart.charttitle.characters.text:=’ excle二维图’
6)改变二维图的标题字体大小
achart.chart.charttitle.font.size:=6;