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