以前一个项目要求将数据导出为Execl和dbf,导出为Excel的代码比较多,我将自己写的导出为dbf的代码贴出,希望给大家有所帮助,思路为提前建好一个空的dbf文件,导出时将该模板复制到工作目录,然后将数据插入该dbf中,当用户下载完毕后将其删除。
1.导出助手类
using System;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Globalization;
using System.Collections;
namespace Web.Controls.Export
{
/// <summary>
/// DbfHelper 导出助手类。
/// </summary>
public class DbfHelper
{
string _templetFile;//DBF模板文件
string _fileName;//目标临时文件
string _serverpath;//
string _fields;
string _fileprefix;
DataTable _dataSource;
public DbfHelper()
{
_serverpath=HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath)+"//";
}
public string TempletFile
{
set { _templetFile = value; }
get { return _templetFile; }
}
public string FilePrefix
{
set { _fileprefix = value; }
get { return _fileprefix; }
}
public string Fields
{
set { _fields = value; }
get { return _fields; }
}
public DataTable DataSource
{
set { _dataSource = value; }
get { return _dataSource; }
}
public void Export()
{
HttpResponse response = HttpContext.Current.Response;
CreateData();
response.Charset = "GB2312";
response.ContentEncoding = Encoding.GetEncoding("GB2312");
response.ContentType = "APPLICATION/OCTET-STREAM";
response.AppendHeader("Content-Disposition", "attachment;filename=" +
HttpUtility.UrlEncode(_fileName));
response.WriteFile(_fileName);
response.Flush();
File.Delete(_fileName);
response.End();
}
private void CreateData()
{
string tempfile=GetRandomFileName();
_fileName=_serverpath+@"Temp/"+tempfile+".dbf";
File.Copy(_serverpath+_templetFile,_fileName,true);
string strConn=@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+_serverpath+@"Temp/"+";Extended Properties=dBASE 5.0";
string sql="";
if(_fields!=null && _fields!=string.Empty)
sql="Select "+_fields+" From [" + tempfile+"]" ;
else
sql="Select * From ["+ tempfile +"]";
OleDbDataAdapter adpt=new OleDbDataAdapter(sql,strConn);
OleDbCommandBuilder bd =new OleDbCommandBuilder (adpt);
bd.QuotePrefix="[";
bd.QuoteSuffix="]";
DataSet mySet=new DataSet();
adpt.Fill (mySet,tempfile);
MoveBatch(_dataSource,mySet.Tables[0]);//批量导出数据
adpt.Update(mySet,tempfile);
}
/** <summary>
/// 得到一个随意的文件名
/// </summary>
/// <returns></returns>
private string GetRandomFileName()
{
Random rnd = new Random((int) (DateTime.Now.Ticks));
string s = rnd.Next(999).ToString();
s= FilePrefix + s;
return s;
}
protected virtual void MoveBatch(DataTable src_dt,DataTable dst_dt)
{
foreach(DataRow dr in src_dt.Rows)
{
dst_dt.ImportRow(dr);
}
}
}
}
2.如何调用
DbfHelper export=new DbfHelper;
export.TempletFile="DATAAIR.DBF";
export.FilePrefix="ASP";
export.DataSource=dt;
export.Fields="[DATE],CYR,DM,SS,HBH,JX,HBXZ,HX,HX0,HXFL,HD,HDFL,ZDYZ,ZDZW,PEYZ,PEZW,KGYZ,KGZW,IO,JCN,QJSJ,CR,ET,YE,CRWH,ETWH,YEWH,XL,YJ,HW,PBM,XG,BC";
export.Export();
3.导出是如果需要将数据做一些处理怎么办?
新建个类继承自DbfHelper,重写MoveBatch方法,在该方法中进行数据转换处理。