Excel管理控件Aspose.Cells功能教程——将数据从Excel导出到C#中的数据表

MS Excel电子表格被广泛用于保留小型,中型或大型数据。在各种情况下,电子表格都充当存储应用程序数据的数据库。

  • 将Excel导出到C#中的DataTable

整合所有格式的Aspose.Total永久授权正在火热促销中,联系客服立马1分钟了解全部咨询!


将Excel导出到C#中的DataTable

将数据从Excel工作表导出到DataTables时,可能有两种情况:数据可以是强类型或非强类型。在这两种情况下,都可以相应地执行Excel到DataTable的转换。让我们看一下如何应对上述两种情况。

将强类型的Excel数据导出到C#中的DataTable

强类型数据表示单列中的值属于特定数据类型。对于这种情况,可以使用以下步骤将Excel数据导出到DataTable。

  1. 使用Workbook类加载Excel文件。
  2. 在工作表对象中获取要导出的工作表。
  3. 使用Worksheet.Cells.ExportDataTable(int,int,int,int,bool)方法将数据导出到DataTable对象。
  4. 使用DataTable作为数据源。

下面的代码示例演示如何使用C#将Excel数据导出到DataTable。

// Create a file stream containing the Excel file to be openedFileStream fstream = new FileStream("Excel.xlsx", FileMode.Open);// Instantiate a Workbook object//Opening the Excel file through the file streamWorkbook workbook = new Workbook(fstream);// Access the first worksheet in the Excel fileWorksheet worksheet = workbook.Worksheets[0];// Export the contents of 2 rows and 2 columns starting from 1st cell to DataTableDataTable dataTable = worksheet.Cells.ExportDataTable(0, 0,2, 2, true);// Bind the DataTable with DataGriddataGridView1.DataSource = dataTable;// Close the file stream to free all resourcesfstream.Close();

将非严格类型的Excel数据导出到C#中的数据表

现在,让我们看一下在工作表中的值不是强类型的另一种情况。这意味着它们不属于特定的数据类型。在这种情况下,以下是将Excel数据导出到DataTable的步骤。

  1. 使用Workbook类加载Excel文件。
  2. 在工作表对象中选择要导出的工作表。
  3. 使用Worksheet.Cells.ExportDataTableAsString(int,int,int,int,bool)方法将数据导出到DataTable对象。
  4. 使用DataTable作为数据源。

下面的代码示例演示如何将非强类型数据从Excel导出到C#中的DataTable。

// Create a file stream containing the Excel file to be openedFileStream fstream = new FileStream("Excel.xlsx", FileMode.Open);// Instantiate a Workbook object//Opening the Excel file through the file streamWorkbook workbook = new Workbook(fstream);// Access the first worksheet in the Excel fileWorksheet worksheet = workbook.Worksheets[0];// Export the contents of 2 rows and 2 columns starting from 1st cell to DataTableDataTable dataTable = worksheet.Cells.ExportDataTableAsString(0, 0, 2, 2, true);// Bind the DataTable with DataGriddataGridView1.DataSource = dataTable;// Close the file stream to free all resourcesfstream.Close();


还想要更多吗可以点击阅读【2020 · Aspose最新资源整合】查找需要的教程资源。如果您有任何疑问或需求,请随时加入Aspose技术交流群(),我们很高兴为您提供查询和咨询
标签:

声明:本站部分文章及图片源自用户投稿,如本站任何资料有侵权请您尽早请联系jinwei@zod.com.cn进行处理,非常感谢!

上一篇 2021年1月25日
下一篇 2021年1月25日

相关推荐

发表回复

登录后才能评论