asp.net与excel互操作实现代码
2024-07-10 12:42:26
供稿:网友
代码如下:
/// <summary>
/// 将datatable中的数据导出到指定的excel文件中
/// </summary>
/// <param name="page">web页面对象</param>
/// <param name="tab">包含被导出数据的datatable对象</param>
/// <param name="filename">excel文件的名称</param>
public static void export(system.web.ui.page page,system.data.datatable tab,string filename)
{
system.web.httpresponse httpresponse = page.response;
system.web.ui.webcontrols.datagrid datagrid=new system.web.ui.webcontrols.datagrid();
datagrid.datasource=tab.defaultview;
datagrid.allowpaging = false;
datagrid.headerstyle.backcolor = system.drawing.color.green;
datagrid.headerstyle.horizontalalign = horizontalalign.center;
datagrid.headerstyle.font.bold = true;
datagrid.databind();
httpresponse.appendheader("content-disposition","attachment;filename="+httputility.urlencode(filename,system.text.encoding.utf8)); //filename="*.xls";
httpresponse.contentencoding=system.text.encoding.getencoding("gb2312");
httpresponse.contenttype ="application/ms-excel";
system.io.stringwriter tw = new system.io.stringwriter() ;
system.web.ui.htmltextwriter hw = new system.web.ui.htmltextwriter (tw);
datagrid.rendercontrol(hw);
string filepath = page.server.mappath("..")+"//files//" +filename;
system.io.streamwriter sw = system.io.file.createtext(filepath);
sw.write(tw.tostring());
sw.close();
downfile(httpresponse,filename,filepath);
httpresponse.end();
}
private static bool downfile(system.web.httpresponse response,string filename,string fullpath)
{
try
{
response.contenttype = "application/octet-stream";
response.appendheader("content-disposition","attachment;filename=" +
httputility.urlencode(filename,system.text.encoding.utf8) + ";charset=gb2312");
system.io.filestream fs= system.io.file.openread(fullpath);
long flen=fs.length;
int size=102400;//每100k同时下载数据
byte[] readdata = new byte[size];//指定缓冲区的大小
if(size>flen)size=convert.toint32(flen);
long fpos=0;
bool isend=false;
while (!isend)
{
if((fpos+size)>flen)
{
size=convert.toint32(flen-fpos);
readdata = new byte[size];
isend=true;
}
fs.read(readdata, 0, size);//读入一个压缩块
response.binarywrite(readdata);
fpos+=size;
}
fs.close();
system.io.file.delete(fullpath);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 将指定excel文件中的数据转换成datatable对象,供应用程序进一步处理
/// </summary>
/// <param name="filepath"></param>
/// <returns></returns>
public static system.data.datatable import(string filepath)
{
system.data.datatable rs = new system.data.datatable();
bool canopen=false;
oledbconnection conn = new oledbconnection("provider=microsoft.jet.oledb.4.0;"+