,欢迎访问网页设计爱好者web开发。前言:
前几天一同事问我如何利用c#将数据导到excel文件当中,当时比较忙没有
顾得上去研究,今天特地研究了一下,基本搞定,下面就具体介绍如何将
dataview中的数据按照一定格式存到excel文件当中。
正文:
一、首先要引用一个excel的组件,我一开始是在office xp下尝试的,不
成功,后来把xp给干掉,装2k,就成功了,所以这里分享的是office 2k下
引用相关组件来实现功能的,在工程中引用com标签中的microsoft 
excel 9.0 object library,添加成功后,引用中会多出三个引用项:
excel、office、vbide。
 
 
 
二、具体代码。
using system;
using system.data;
using excel;
using system.io;
namespace test.excelcom
{
/// <summary>
/// 将dataview中的数据导入excel文件中
/// 作者:rexsp
/// 创建:2004-4-4
/// </summary>
public class outputexcel
{
 #region 私有成员
 /// <summary>
 /// 数据的dataview
 /// </summary>
 private dataview dv=null;
 /// <summary>
 /// 表格标题
 /// </summary>
 private string title=null;
 /// <summary>
 /// 输出文件路径
 /// </summary>
 private string outfilepath=null;
 /// <summary>
 /// 输入文件名
 /// </summary>
 private string inputfilepath=null;
 #endregion
 #region 公共属性
 /// <summary>
 /// 数据的dataview
 /// </summary>
 public dataview dv
 {
 set{dv=value;}
 }
 /// <summary>
 /// 表格标题
 /// </summary>
 public string title
 {
 set{title=value;}
 get{return title;}
 }
 /// <summary>
 /// 输出文件路径
 /// </summary>
 public string outfilepath
 {
 set{outfilepath=value;}
 get{return outfilepath;}
 }
 /// <summary>
 /// 输入文件路径
 /// </summary>
 public string inputfilepath
 {
 set{inputfilepath=value;}
 get{return inputfilepath;}
 }
 #endregion
 
 #region 构造函数
 public outputexcel()
 {
 }
 public outputexcel(dataview dv,string title)
 {
 //
 // todo: 在此处添加构造函数逻辑
 //
 }
 #endregion
 #region 公共方法
 public void createexcel()
 {
 int rowindex=4;//行起始坐标
 int colindex=1;//列起始坐标
 applicationclass myapp=null;
 workbook mybook=null;
 worksheet mysheet=null;
 //如果文件不存在,则将模板文件拷贝一份作为输出文件
 //这里如果通过file.create来创建文件是不行的,因为xls
 //的空文件也有固定的格式,跟文本不一样的,也许有其它
 //通过程序直接生成excel的方法,大家可以尝试尝试的
 if(!file.exists(outfilepath))
 {
 file.copy(inputfilepath,outfilepath,true);
 }
 myapp= new applicationclass();
 myapp.visible=false;
 object omissiong=system.reflection.missing.value;
 myapp.workbooks.open(outfilepath,omissiong,omissiong,omissiong,omissiong,
omissiong,omissiong,omissiong,omissiong,omissiong,omissiong,omissiong,omissiong);
 mybook=myapp.workbooks[1];
 mysheet=(worksheet)mybook.activesheet;
 //
 //取得标题
 //
 foreach(datacolumn col in dv.table.columns)
 {
 colindex++;
 mysheet.cells[4,colindex] = col.columnname;
 mysheet.get_range(mysheet.cells[4,colindex],mysheet.cells[4,colindex]).horizontalalignment = xlvalign.xlvaligncenter;
//设置标题格式为居中对齐
 }
 //
 //取得表格中的数据
 //
 foreach(datarowview row in dv)
 {
 rowindex ++;
 colindex = 1;
 foreach(datacolumn col in dv.table.columns)
 {
 colindex ++;
 if(col.datatype == system.type.gettype("system.datetime"))
 {
 mysheet.cells[rowindex,colindex] = (convert.todatetime(row[col.columnname].tostring())).tostring("yyyy-mm-dd");
 mysheet.get_range(mysheet.cells[rowindex,colindex],mysheet.cells[rowindex,colindex]).horizontalalignment = xlvalign.xlvaligncenter;//设置日期型的字段格式为居中对齐
 }
 else
 if(col.datatype == system.type.gettype("system.string"))
 {
 mysheet.cells[rowindex,colindex] = "'"+row[col.columnname].tostring();
 mysheet.get_range(mysheet.cells[rowindex,colindex],mysheet.cells[rowindex,colindex]).horizontalalignment = xlvalign.xlvaligncenter;//设置字符型的字段格式为居中对齐
 }
 else
 {
 mysheet.cells[rowindex,colindex] = row[col.columnname].tostring();
 }
 }
 }
 //
 //加载一个合计行
 //
 int rowsum = rowindex + 1;
 int colsum = 2;
 mysheet.cells[rowsum,2] = "合计";
 mysheet.get_range(mysheet.cells[rowsum,2],mysheet.cells[rowsum,2]).horizontalalignment = xlhalign.xlhaligncenter;
 //
 //设置选中的部分的颜色
 //
 mysheet.get_range(mysheet.cells[rowsum,colsum],mysheet.cells[rowsum,colindex]).select();
 mysheet.get_range(mysheet.cells[rowsum,colsum],mysheet.cells[rowsum,colindex]).interior.colorindex = 19;//设置为浅黄色,共计有56种
 //
 //取得整个报表的标题
 //
 mysheet.cells[2,2] = title;
 //
 //设置整个报表的标题格式
 //
 mysheet.get_range(mysheet.cells[2,2],mysheet.cells[2,2]).font.bold = true;
 mysheet.get_range(mysheet.cells[2,2],mysheet.cells[2,2]).font.size = 22;
 //
 //设置报表表格为最适应宽度
 //
 mysheet.get_range(mysheet.cells[4,2],mysheet.cells[rowsum,colindex]).select();
 mysheet.get_range(mysheet.cells[4,2],mysheet.cells[rowsum,colindex]).columns.autofit();
 //
 //设置整个报表的标题为跨列居中
 //
 mysheet.get_range(mysheet.cells[2,2],mysheet.cells[2,colindex]).select();
 mysheet.get_range(mysheet.cells[2,2],mysheet.cells[2,colindex]).horizontalalignment = xlhalign.xlhaligncenteracrossselection;
 //
 //绘制边框
 //
 mysheet.get_range(mysheet.cells[4,2],mysheet.cells[rowsum,colindex]).borders.linestyle = 1;
 mysheet.get_range(mysheet.cells[4,2],mysheet.cells[rowsum,2]).borders[xlbordersindex.xledgeleft].weight = xlborderweight.xlthick;//设置左边线加粗
 mysheet.get_range(mysheet.cells[4,2],mysheet.cells[4,colindex]).borders[xlbordersindex.xledgetop].weight = xlborderweight.xlthick;//设置上边线加粗
 mysheet.get_range(mysheet.cells[4,colindex],mysheet.cells[rowsum,colindex]).borders[xlbordersindex.xledgeright].weight = xlborderweight.xlthick;//设置右边线加粗
 mysheet.get_range(mysheet.cells[rowsum,2],mysheet.cells[rowsum,colindex]).borders[xlbordersindex.xledgebottom].weight = xlborderweight.xlthick;//设置下边线加粗
 mybook.save();;
 mybook.close( true,outfilepath,true);
 system.runtime.interopservices.marshal.releasecomobject(mysheet);
 system.runtime.interopservices.marshal.releasecomobject(mybook);
 system.runtime.interopservices.marshal.releasecomobject(myapp);
 gc.collect();
 }
 #endregion
}
}
一点说明:操作excel的时候,可能会发生excel进程被锁定,无法退
出,解决方法是在保存完并关闭mybook(工作簿)后,别关闭excel进
程(//myapp.quit();)。这样的结果是服务器上始终有一个excel的
进程。可能会出现asp_net用户操作excel的权限不够,配置dcom。运
行dcomcnfg.exe,找到excel应用程序,配置其属性,身份验证级别
选"无",身份标识选"交互式用户",安全性页面,启动和访问均给
everyone。注意:查看当前进程中是否有winword进程存在,如果有且
不能被结束,那么重启动计算机。再次运行你的代码即ok。这样以后
就不会出现权限不够的情况了。
三、调用
#region 测试excel
quickitemcollection qic =new quickitemcollection();
qic.getallinfo();
dataview dv= new dataview();
datatable dt = new datatable("excel");
dt.columns.add("id",system.type.gettype("system.string"));
dt.columns.add("itemname",system.type.gettype("system.string"));
int qiccount=qic.count;
for(int i=0;i<qiccount;i++)
{
 datarow dr= dt.newrow();
 dr[0] = qic[i].id;
 dr[1] = qic[i].itemname;
 dt.rows.add(dr);
}
outputexcel ope = new outputexcel(); 
ope.dv=dt.defaultview;
ope.title="测试生成excel";
ope.inputfilepath=server.mappath("sample.xls");
ope.outfilepath=server.mappath("test.xls");
ope.createexcel();
#endregion
一点说明:这段代码的前半部分读过我那篇《一种快速存取订阅条目的方
案》的读者应该认得的,其实也就是一个把集合类中数据填充到
dataview中的过程,后面的就是调用。sample.xls是个新建的空的
sample.xls,然后执行完毕后,就会生成test.xls文档,我执行后的
结果如下图: