在C#中,NPOI是一个流行的开源库,用于读写Excel、Word和其他Office格式的文件。如果你想要使用NPOI来利用DataTable批量读写Excel,以下是一个基本的步骤指南:
- 安装NPOI NuGet包:
首先,你需要在你的C#项目中安装NPOI库。可以通过NuGet包管理器来安装。
shellInstall-Package NPOI -Version [DesiredVersion]
- 读取Excel文件到DataTable:
假设你有一个Excel文件,你想将其内容读取到一个DataTable中。
csharpusing NPOI.SS.UserModel;
using NPOI.XSSF.UserModel; // For .xlsx
using NPOI.HSSF.UserModel; // For .xls
using System.Data;
using System.IO;
public DataTable ReadExcelToDataTable(string filePath)
{
IWorkbook workbook;
using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
if (Path.GetExtension(filePath).Equals(".xls")) // For Excel 97-2003 (.xls)
{
workbook = new HSSFWorkbook(file);
}
else // For Excel 2007 (.xlsx)
{
workbook = new XSSFWorkbook(file);
}
}
ISheet sheet = workbook.GetSheetAt(0); // Get the first sheet
DataTable dt = new DataTable();
IRow headerRow = sheet.GetRow(0); // Assume the first row is header
int cellCount = headerRow.LastCellNum;
for (int i = headerRow.FirstCellNum; i < cellCount; i++)
{
dt.Columns.Add(headerRow.GetCell(i).ToString());
}
int rowCount = sheet.LastRowNum;
for (int i = (sheet.FirstRowNum); i <= rowCount; i++)
{
IRow row = sheet.GetRow(i);
DataRow dataRow = dt.NewRow();
for (int j = row.FirstCellNum; j < cellCount; j++)
{
dataRow[j] = row.GetCell(j).ToString();
}
dt.Rows.Add(dataRow);
}
return dt;
}
- 将DataTable写入Excel文件:
如果你想将一个DataTable的内容写入Excel文件,你可以使用以下方法:
csharppublic void WriteDataTableToExcel(DataTable dt, string filePath)
{
IWorkbook workbook;
ISheet sheet;
if (Path.GetExtension(filePath).Equals(".xls")) // For Excel 97-2003 (.xls)
{
workbook = new HSSFWorkbook();
sheet = workbook.CreateSheet("Sheet1"); // Create a new sheet named "Sheet1"
}
else // For Excel 2007 (.xlsx)
{
workbook = new XSSFWorkbook(); // Use .xlsx format workbook for .xlsx file extension
sheet = workbook.CreateSheet("Sheet1"); // Create a new sheet named "Sheet1" in .xlsx format workbook
}
// Write the column names as header rows
IRow headerRow = sheet.CreateRow(0);
for (int i = 0; i < dt.Columns.Count; i++)
{
headerRow.CreateCell(i).SetCellValue(dt.Columns[i].ColumnName);
}
// Create a new row and get its cell and set the value
int rowCount = dt.Rows.Count;
for (int i = 0; i < rowCount; i++)
{
IRow row = sheet.CreateRow(i + 1);
for (int j = 0; j < dt.Columns.Count; j++)
{
row.CreateCell(j).SetCellValue(dt.Rows[i][j].ToString());
}
}
// Write the workbook to a file stream
using (FileStream file = new FileStream(filePath, FileMode.Create, FileAccess.Write))
workbook.Write(file);
}
4. 使用OleDb连接读取和写入:
如果你需要与Excel交互,并且你的数据源是一个Excel文件,那么你可以使用OleDb来连接它。在.NET中,你可以使用`System.Data.OleDb`命名空间来做到这一点。
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\path\\to\\your\\excel.xlsx;Extended Properties='Excel 12.0 Xml;HDR=YES;'";
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
DataTable dt = new DataTable();
string query = "SELECT * FROM [Sheet1$]"; // Assuming your data starts in Sheet1
using (OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn))
{
adapter.Fill(dt);
}
// ... do something with the DataTable ...
// To write back to the Excel sheet:
string updateQuery = "UPDATE [Sheet1$] SET ColumnName = 'NewValue' WHERE SomeColumn = 'SomeValue'";
using (OleDbCommand cmd = new OleDbCommand(updateQuery, conn))
{
cmd.ExecuteNonQuery();
}
}
注意:当使用OleDb连接到Excel时,请确保你的Excel文件的路径和名称正确,并且你的查询和更新语句也正确地指向了你的数据。同时,处理更新操作时要特别小心,因为这会直接更改原始Excel文件。
这些代码示例提供了如何使用NPOI库来读取和写入Excel文件的基本方法。你可以根据实际需求调整代码以适应你的应用程序。
本文暂时没有评论,来添加一个吧(●'◡'●)