asp.net與excel互操作實現(xiàn)代碼
更新時間:2010年04月01日 18:34:25 作者:
將datatable中的數(shù)據(jù)導出到指定的excel文件中
復制代碼 代碼如下:
/// <summary>
/// 將datatable中的數(shù)據(jù)導出到指定的excel文件中
/// </summary>
/// <param name="page">web頁面對象</param>
/// <param name="tab">包含被導出數(shù)據(jù)的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同時下載數(shù)據(jù)
byte[] readdata = new byte[size];//指定緩沖區(qū)的大小
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文件中的數(shù)據(jù)轉(zhuǎn)換成datatable對象,供應(yīng)用程序進一步處理
/// </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;"+
"data source=" + filepath + ";" +
"extended properties=\"excel 8.0;\"");
try//嘗試數(shù)據(jù)連接是否可用
{
conn.open();
conn.close();
canopen=true;
}
catch{}
if(canopen)
{
try//如果數(shù)據(jù)連接可以打開則嘗試讀入數(shù)據(jù)
{
oledbcommand myoledbcommand = new oledbcommand("select * from [sheet1$]",conn);
oledbdataadapter mydata = new oledbdataadapter(myoledbcommand);
mydata.fill(rs);
conn.close();
}
catch//如果數(shù)據(jù)連接可以打開但是讀入數(shù)據(jù)失敗,則從文件中提取出工作表的名稱,再讀入數(shù)據(jù)
{
string sheetname=getsheetname(filepath);
if(sheetname.length>0)
{
oledbcommand myoledbcommand = new oledbcommand("select * from ["+sheetname+"$]",conn);
oledbdataadapter mydata = new oledbdataadapter(myoledbcommand);
mydata.fill(rs);
conn.close();
}
}
}
else
{
system.io.streamreader tmpstream=file.opentext(filepath);
string tmpstr=tmpstream.readtoend();
tmpstream.close();
rs=getdatatablefromstring(tmpstr);
tmpstr="";
}
return rs;
}
/// <summary>
/// 將指定html字符串的數(shù)據(jù)轉(zhuǎn)換成datatable對象 --根據(jù)“<tr><td>”等特殊字符進行處理
/// </summary>
/// <param name="tmphtml">html字符串</param>
/// <returns></returns>
private static datatable getdatatablefromstring(string tmphtml)
{
string tmpstr=tmphtml;
datatable tb=new datatable();
//先處理一下這個字符串,刪除第一個<tr>之前合最后一個</tr>之后的部分
int index=tmpstr.indexof("<tr");
if(index>-1)
tmpstr=tmpstr.substring(index);
else
return tb;
index=tmpstr.lastindexof("</tr>");
if(index>-1)
tmpstr=tmpstr.substring(0,index+5);
else
return tb;
bool existssparator=false;
char separator=convert.tochar("^");
//如果原字符串中包含分隔符“^”則先把它替換掉
if(tmpstr.indexof(separator.tostring())>-1)
{
existssparator=true;
tmpstr=tmpstr.replace("^","^$&^");
}
//先根據(jù)“</tr>”分拆
string[] tmprow=tmpstr.replace("</tr>","^").split(separator);
for(int i=0;i<tmprow.length-1;i++)
{
datarow newrow=tb.newrow();
string tmpstri=tmprow[i];
if(tmpstri.indexof("<tr")>-1)
{
tmpstri=tmpstri.substring(tmpstri.indexof("<tr"));
if(tmpstri.indexof("display:none")<0||tmpstri.indexof("display:none")>tmpstri.indexof(">"))
{
tmpstri=tmpstri.replace("</td>","^");
string[] tmpfield=tmpstri.split(separator);
for(int j=0;j<tmpfield.length-1;j++)
{
tmpfield[j]=removestring(tmpfield[j],"<font>");
index=tmpfield[j].lastindexof(">")+1;
if(index>0)
{
string field=tmpfield[j].substring(index,tmpfield[j].length-index);
if(existssparator) field=field.replace("^$&^","^");
if(i==0)
{
string tmpfieldname=field;
int sn=1;
while(tb.columns.contains(tmpfieldname))
{
tmpfieldname=field+sn.tostring();
sn+=1;
}
tb.columns.add(tmpfieldname);
}
else
{
newrow[j]=field;
}
}//end of if(index>0)
}
if(i>0)
tb.rows.add(newrow);
}
}
}
tb.acceptchanges();
return tb;
}
/// <summary>
/// 從指定html字符串中剔除指定的對象
/// </summary>
/// <param name="tmphtml">html字符串</param>
/// <param name="remove">需要剔除的對象--例如輸入"<font>"則剔除"<font ???????>"和"</font>>"</param>
/// <returns></returns>
public static string removestring(string tmphtml,string remove)
{
tmphtml=tmphtml.replace(remove.replace("<","</"),"");
tmphtml=removestringhead(tmphtml,remove);
return tmphtml;
}
/// <summary>
/// 只供方法removestring()使用
/// </summary>
/// <returns></returns>
private static string removestringhead(string tmphtml,string remove)
{
//為了方便注釋,假設(shè)輸入?yún)?shù)remove="<font>"
if(remove.length<1) return tmphtml;//參數(shù)remove為空:不處理返回
if((remove.substring(0,1)!="<")||(remove.substring(remove.length-1)!=">")) return tmphtml;//參數(shù)remove不是<?????>:不處理返回
int indexs=tmphtml.indexof(remove.replace(">",""));//查找“<font”的位置
int indexe=-1;
if(indexs>-1)
{
string tmpright=tmphtml.substring(indexs,tmphtml.length-indexs);
indexe=tmpright.indexof(">");
if(indexe>-1)
tmphtml=tmphtml.substring(0,indexs)+tmphtml.substring(indexs+indexe+1);
if(tmphtml.indexof(remove.replace(">",""))>-1)
tmphtml=removestringhead(tmphtml,remove);
}
return tmphtml;
}
/// <summary>
/// 將指定excel文件中讀取第一張工作表的名稱
/// </summary>
/// <param name="filepath"></param>
/// <returns></returns>
private static string getsheetname(string filepath)
{
string sheetname="";
system.io.filestream tmpstream=file.openread(filepath);
byte[] filebyte=new byte[tmpstream.length];
tmpstream.read(filebyte,0,filebyte.length);
tmpstream.close();
byte[] tmpbyte=new byte[]{convert.tobyte(11),convert.tobyte(0),convert.tobyte(0),convert.tobyte(0),convert.tobyte(0),convert.tobyte(0),convert.tobyte(0),convert.tobyte(0),
convert.tobyte(11),convert.tobyte(0),convert.tobyte(0),convert.tobyte(0),convert.tobyte(0),convert.tobyte(0),convert.tobyte(0),convert.tobyte(0),
convert.tobyte(30),convert.tobyte(16),convert.tobyte(0),convert.tobyte(0)};
int index=getsheetindex(filebyte,tmpbyte);
if(index>-1)
{
index+=16+12;
system.collections.arraylist sheetnamelist=new system.collections.arraylist();
for(int i=index;i<filebyte.length-1;i++)
{
byte temp=filebyte[i];
if(temp!=convert.tobyte(0))
sheetnamelist.add(temp);
else
break;
}
byte[] sheetnamebyte=new byte[sheetnamelist.count];
for(int i=0;i<sheetnamelist.count;i++)
sheetnamebyte[i]=convert.tobyte(sheetnamelist[i]);
sheetname=system.text.encoding.default.getstring(sheetnamebyte);
}
return sheetname;
}
/// <summary>
/// 只供方法getsheetname()使用
/// </summary>
/// <returns></returns>
private static int getsheetindex(byte[] findtarget,byte[] finditem)
{
int index=-1;
int finditemlength=finditem.length;
if(finditemlength<1) return -1;
int findtargetlength=findtarget.length;
if((findtargetlength-1)<finditemlength) return -1;
for(int i=findtargetlength-finditemlength-1;i>-1;i--)
{
system.collections.arraylist tmplist=new system.collections.arraylist();
int find=0;
for(int j=0;j<finditemlength;j++)
{
if(findtarget[i+j]==finditem[j]) find+=1;
}
if(find==finditemlength)
{
index=i;
break;
}
}
return index;
}
相關(guān)文章
asp.net 在global中攔截404錯誤的實現(xiàn)方法
asp.net 在global中攔截404錯誤,增加用于體驗,不會因為提示找不到信息而直接退出的尷尬。2010-03-03asp.net SqlParameter如何根據(jù)條件有選擇的添加參數(shù)
有時候?qū)憇ql語句的時候會根據(jù)方法傳進來的參數(shù)來判斷sql語句中where條件的參數(shù),下面有個示例,大家可以參考下2014-06-06Asp.net MVC利用knockoutjs實現(xiàn)登陸并記錄用戶的內(nèi)外網(wǎng)IP及所在城市(推薦)
這篇文章主要介紹了 Asp.net MVC利用knockoutjs實現(xiàn)登陸并記錄用戶的內(nèi)外網(wǎng)IP及所在城市(推薦),需要的朋友可以參考下2017-02-02asp.net實現(xiàn)訪問局域網(wǎng)共享目錄下文件的解決方法
這篇文章主要介紹了asp.net實現(xiàn)訪問局域網(wǎng)共享目錄下文件的解決方法,需要的朋友可以參考下2014-07-07.Net Core WebApi部署在Linux服務(wù)器上的方法
這篇文章主要介紹了.Net Core WebApi部署在Linux服務(wù)器上的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-03-03