C# NPOI读取.xls
时间: 2023-08-18 22:11:05 浏览: 236
您可以使用C#的NPOI库来读取.xls文件。首先,您需要使用`ReadFromExcelFile`方法来读取文件并将数据存储在一个DataTable中。该方法使用`IWorkbook`接口来打开文件,并根据文件的扩展名选择适当的工作簿类型。然后,它遍历每一行和每一列,将单元格的值存储在DataTable中。最后,您可以使用`DataTableToExcel`方法将DataTable中的数据写入到.xls文件中。
以下是一个示例代码,演示了如何使用NPOI库读取.xls文件:
```csharp
public void ReadFromExcelFile(string filePath)
{
IWorkbook wk = null;
string extension = System.IO.Path.GetExtension(filePath);
try
{
FileStream fs = File.OpenRead(filePath);
if (extension.Equals(".xls"))
{
wk = new HSSFWorkbook(fs);
}
else
{
wk = new XSSFWorkbook(fs);
}
fs.Close();
ISheet sheet = wk.GetSheetAt(0);
IRow row = sheet.GetRow(0);
int offset = 0;
for (int i = 0; i <= sheet.LastRowNum; i++)
{
row = sheet.GetRow(i);
if (row != null)
{
for (int j = 0; j < row.LastCellNum; j++)
{
string value = row.GetCell(j).ToString();
Console.Write(value.ToString() + " ");
}
Console.WriteLine("\n");
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
```
您还可以使用`OpenFileDialog`来选择要读取的.xls文件。以下是一个示例代码,演示了如何使用`OpenFileDialog`选择.xls文件:
```csharp
private void Button_SelcetFile_Click(object sender, EventArgs e)
{
OpenFileDialog OFD = new OpenFileDialog();
OFD.Filter = "xls files (*.xls)|*.xls|All files (*.*)|*.*";
OFD.RestoreDirectory = true;
if (OFD.ShowDialog() == DialogResult.OK)
{
string filePath = OFD.FileName;
ReadFromExcelFile(filePath);
}
}
```
希望这可以帮助到您!
#### 引用[.reference_title]
- *1* [c#:使用NPOI读取excel表格](https://blog.csdn.net/weixin_44899642/article/details/124687499)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* [C# —— 使用C# NPOI 读取Excel(.xls)文件](https://blog.csdn.net/cdefg198/article/details/7844305)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item]
- *3* [C#中NPOI操作excel之读取和写入excel数据](https://blog.csdn.net/coderK2014/article/details/50185163)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文