首页 > 代码库 > DataTable转CSV
DataTable转CSV
/// <summary>
/// 将DataTable中数据写入到CSV文件中
/// </summary>
/// <param name="dt">提供保存数据的DataTable</param>
/// <param name="fileName">CSV的文件路径</param>
public void SaveCSV(DataTable dt, string fileName)
{
FileStream fs = new FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
string datahttp://www.mamicode.com/= "";
//写出列名称
//for (int i = 0; i < dt.Columns.Count; i++)
//{
// data += dt.Columns[i].ColumnName.ToString();
// if (i < dt.Columns.Count - 1)
// {
// data += ",";
// }
//}
//sw.WriteLine(data);
//写出各行数据
for (int i = 0; i < dt.Rows.Count; i++)
{
datahttp://www.mamicode.com/= "";
for (int j = 0; j < dt.Columns.Count; j++)
{
data += dt.Rows[i][j].ToString();
if (j < dt.Columns.Count - 1)
{
data += ",";
}
}
sw.WriteLine(data);
}
sw.Close();
fs.Close();
DispMsg("CSV文件保存成功!");
}
public static void DataTabletoCVS(DataTable dt, string saveFile)
{
var rptExcel = new Microsoft.Office.Interop.Excel.Application();
int rowCount = dt.Rows.Count;//行数
int columnCount = dt.Columns.Count;//列数
int rowIndex = 1;
int colindex = 1;
Microsoft.Office.Interop.Excel.Workbook workbook = rptExcel.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
var worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets.get_Item(1);
//rptExcel.Visible = true;//打开导出的Excel文件
//创建对象数组存储DataTable的数据,这样的效率比直接将Datateble的数据填充worksheet.Cells[row,col]高
object[,] objData = http://www.mamicode.com/new object[rowCount, columnCount];
//填充内容到对象数组
for (int r = 0; r < rowCount; r++)
{
for (int col = 0; col < columnCount - 1; col++)
{
string strvalue = http://www.mamicode.com/dt.Rows[r][col].ToString();
// objData[r, col] =strvalue ;
double idef=0;
if (double.TryParse(strvalue, out idef))
{
//将对象数组的值赋给Excel对象
Microsoft.Office.Interop.Excel.Range rangecell = worksheet.get_Range(worksheet.Cells[r + 1, col + 1], worksheet.Cells[r + 1, col + 1]);
rangecell.Value2 = double.Parse(strvalue);
rangecell.NumberFormat = "0";
}
}
}
//将对象数组的值赋给Excel对象
//Microsoft.Office.Interop.Excel.Range range = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[rowCount, columnCount]);
//range.Value2 = objData;
try
{
workbook.Saved = true;
workbook.SaveCopyAs(saveFile);//以复制的形式保存在已有的文档里
}
catch (Exception ex)
{
LoggerWriter.Error(ex);
}
finally
{
dt.Dispose();
rptExcel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(rptExcel);
System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
}
}
DataTable转CSV