csv(comma-separated values)是以逗号间隔的文本文件,此类文件以纯文本形式存储表格数据。通常,csv文件可以用ms excel打开。
文本将介绍如何使用spire.xls将如下的csv文件转换为excel文件,pdf文件,以及导出数据到datatable。
转csv到excel
c#
//初始化workbook对象
workbook wb = new workbook();
//加载csv文件
wb.loadfromfile("samplecsvfile.csv", ",",1,1);
//将第一个工作表命名为“导入excel”
wb.worksheets[0].name = "导入excel";
//转换为excel文件
wb.savetofile("toexcel.xlsx", excelversion.version2013);
vb.net
'初始化workbook对象
dim wb as new workbook()
'加载csv文件
wb.loadfromfile("samplecsvfile.csv", ",", 1, 1)
'将第一个工作表命名为“导入excel”
wb.worksheets(0).name = "导入excel"
'转换为excel文件
wb.savetofile("toexcel.xlsx", excelversion.version2013)
转csv到pdf
c#
//初始化workbook对象
workbook wb = new workbook();
//加载csv文件
wb.loadfromfile("samplecsvfile.csv", ",",1,1);
//将一个工作表的内容转换到一页pdf上
wb.convertersetting.sheetfittopage = true;
//自动调整列宽使适应文字长度
worksheet sheet = wb.worksheets[0];
for (int i = 1; i < sheet.columns.length; i )
{
sheet.autofitcolumn(i);
}
//保存为pdf文件
sheet.savetopdf("topdf.pdf");
vb.net
'初始化workbook对象
dim wb as new workbook()
'加载csv文件
wb.loadfromfile("samplecsvfile.csv", ",", 1, 1)
'将一个工作表的内容转换到一页pdf上
wb.convertersetting.sheetfittopage = true
'自动调整列宽使适应文字长度
dim sheet as worksheet = wb.worksheets(0)
for i as integer = 1 to sheet.columns.length - 1
sheet.autofitcolumn(i)
next
'保存为pdf文件
sheet.savetopdf("topdf.pdf")
将csv数据导入datatable
c#
private void btnimport_click(object sender, eventargs e)
{
//创建openfiledialog实例
openfiledialog dialog = new openfiledialog();
//设置过滤
dialog.filter = "csv document(*.csv)|*.csv";
//显示打开文件对话框
dialogresult result = dialog.showdialog();
if (result == dialogresult.ok)
{
//获取csv文件名
string csvfile = dialog.filename;
//加载csv文档到workbook对象
workbook wb = new workbook();
wb.loadfromfile(csvfile,",");
//将第一个工作表导出为datatable
system.data.datatable datatable = wb.worksheets[0].exportdatatable();
//在datagridviewer中显示数据
this.datagridview1.datasource = datatable;
}
}
vb.net
private sub btnimport_click(sender as object, e as eventargs)
'创建openfiledialog实例
dim dialog as new openfiledialog()
'设置过滤
dialog.filter = "csv document(*.csv)|*.csv"
'显示打开文件对话框
dim result as dialogresult = dialog.showdialog()
if result = dialogresult.ok then
'获取csv文件名
dim csvfile as string = dialog.filename
'加载csv文档到workbook对象
dim wb as new workbook()
wb.loadfromfile(csvfile, ",")
'将第一个工作表导出为datatable
dim datatable as system.data.datatable = wb.worksheets(0).exportdatatable()
'在datagridviewer中显示数据
me.datagridview1.datasource = datatable
end if
end sub