翻譯|使用教程|編輯:李顯亮|2021-01-28 09:57:11.687|閱讀 263 次
概述:在各種情況下,電子表格都充當存儲應用程序數據的數據庫。在這種情況下,可能需要從Web或桌面應用程序中讀取存儲在Excel文件中的數據。對于這種情況,本文介紹如何將數據從Excel工作表導出到C#中的數據表。
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
相關鏈接:
MS Excel電子表格被廣泛用于保留小型,中型或大型數據。在各種情況下,電子表格都充當存儲應用程序數據的數據庫。
在這種情況下,可能需要從Web或桌面應用程序中讀取存儲在Excel文件中的數據。對于這種情況,本文介紹如何將數據從Excel工作表導出到C#中的數據表。
Aspose.Cells for .NET是一個類庫,可讓您在.NET應用程序中實現Excel自動化功能。此外,該API允許您在幾個步驟中將數據從Excel工作表導出到ADO.NET DataTable。擊下方按鈕可以下載API的安裝包。
將數據從Excel工作表導出到DataTables時,可能有兩種情況:數據可以是強類型或非強類型。在這兩種情況下,都可以相應地執行Excel到DataTable的轉換。讓我們看一下如何應對上述兩種情況。
強類型數據表示單列中的值屬于特定數據類型。對于這種情況,可以使用以下步驟將Excel數據導出到DataTable。
下面的代碼示例演示如何使用C#將Excel數據導出到DataTable。
// Create a file stream containing the Excel file to be opened FileStream fstream = new FileStream("Excel.xlsx", FileMode.Open); // Instantiate a Workbook object //Opening the Excel file through the file stream Workbook workbook = new Workbook(fstream); // Access the first worksheet in the Excel file Worksheet worksheet = workbook.Worksheets[0]; // Export the contents of 2 rows and 2 columns starting from 1st cell to DataTable DataTable dataTable = worksheet.Cells.ExportDataTable(0, 0,2, 2, true); // Bind the DataTable with DataGrid dataGridView1.DataSource = dataTable; // Close the file stream to free all resources fstream.Close();
現在,讓我們看一下在工作表中的值不是強類型的另一種情況。這意味著它們不屬于特定的數據類型。在這種情況下,以下是將Excel數據導出到DataTable的步驟。
下面的代碼示例演示如何將非強類型數據從Excel導出到C#中的DataTable。
// Create a file stream containing the Excel file to be opened FileStream fstream = new FileStream("Excel.xlsx", FileMode.Open); // Instantiate a Workbook object //Opening the Excel file through the file stream Workbook workbook = new Workbook(fstream); // Access the first worksheet in the Excel file Worksheet worksheet = workbook.Worksheets[0]; // Export the contents of 2 rows and 2 columns starting from 1st cell to DataTable DataTable dataTable = worksheet.Cells.ExportDataTableAsString(0, 0, 2, 2, true); // Bind the DataTable with DataGrid dataGridView1.DataSource = dataTable; // Close the file stream to free all resources fstream.Close();
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn