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);//此处要修改为:dst_dt.Rows.Add(dr.ItemArray);
}
}
}
}
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方法,在该方法中进行数据转换处理。