C#_把dataTable数据导出到CSV,XLS文件

本文介绍了一个用于将DataTable数据导出为CSV和Excel文件的方法。提供了详细的代码实现,包括读取模板、处理数据并写入文件的过程。适用于需要批量转换数据格式的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//*******
作者: wesimy
时间: 07/31/05
版本: v.2.1
函数名: DatatableToCSVFile
参数说明: DataTable dt 导出CSV的数据
string xbkPahth CSV模板,主要存储一些表头的格式
string SavePath 导出的路径
ref string err 出错提示
功能: 把DataTable的数据导出到CSV文件中
********//
public void DatatableToCSVFile(System.Data.DataTable dt, string xbkPath, string SavePath, ref string err)
{
string row;
try
{
string header;
string tmp;
StreamReader sr=new StreamReader(xbkPath);
header=sr.ReadLine();

sr.Close();
FileStream fs=File.Create(SavePath);
StreamWriter sw= new StreamWriter (fs);
sw.WriteLine(header);
foreach(DataRow dr in dt.Rows)
{
row="";
for(int i=0;i<dt.Columns.Count;i++)
{
if(i!=dt.Columns.Count-1)
{
tmp= dr[i].ToString().Trim().Replace(","," ");
row=row+tmp+",";
}
else
{
tmp= dr[i].ToString().Trim().Replace(",",".");
row=row+tmp;
}
}
sw.WriteLine(row);
}
sw.Flush();
sw.Close();
}
catch(Exception ex)
{
err=ex.ToString();

}
}
//*******
作者: wesimy
时间: 07/31/05
版本: v.2.1
函数名: DatatableToExelFile
参数说明: DataTable dt 导出xls的数据
string xbkPahth xls模板,主要存储一些表头的格式
string SavePath 导出的路径
ref string err 出错提示
功能: 把DataTable的数据导出到CSV文件中
说明: 需要用到Excel名称空间等,此外,在不同版本的OFFICE可能会导致在BUILD的时候某些方法的错误,看看参数就可以确定用哪个方法了....
********//
public void DatatableToExcelFile( System.Data.DataTable dt,string xbkPath, string SavePath, ref string err)
{
try
{
Excel.Application excel;
Excel._Workbook xBk ;
Excel._Worksheet xSt;

excel = new Excel.ApplicationClass();

xBk = excel.Workbooks.Open (@xbkPath,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing);
xSt = (_Worksheet)xBk.Worksheets["OSI Full inspection result"];
int beginRow = 5;
for(int i=0; i<dt.Rows.Count;i++)
{
for(int j=1;j<dt.Columns.Count+1;j++)
{
xSt.Cells[i+beginRow,j]=dt.Rows[i][j-1];
}
}
xSt.SaveAs(@SavePath,Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing);
excel.Visible=false;
if(xBk != null)
xBk.Close(false, xbkPath, Type.Missing);
if(xBk != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject (xBk);
xBk=null;
if(xSt != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject (xSt);
xSt = null;

if(excel != null)
{
excel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject (excel);
excel = null;
}
}
catch(Exception ex)
{
err = ex.Message;
}

}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值