vc++(vs2010)读写excel文件代码(附示例)收藏 vc++(vs2010)读写excel文件代码(
时间: 2024-01-19 07:00:42 浏览: 84
在VS2010中,可以使用第三方库来读写Excel文件,比如使用NPOI,以下是一个示例代码:
示例1:读取Excel文件
```csharp
using System;
using System.Data;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
public class ExcelReader
{
public DataTable ReadExcel(string filePath)
{
DataTable dataTable = new DataTable();
using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
IWorkbook workbook = new HSSFWorkbook(fileStream);
ISheet sheet = workbook.GetSheetAt(0);
// 获取第一行作为表头
IRow headerRow = sheet.GetRow(0);
int cellCount = headerRow.LastCellNum;
for (int i = headerRow.FirstCellNum; i < cellCount; i++)
{
ICell cell = headerRow.GetCell(i);
dataTable.Columns.Add(cell.StringCellValue);
}
// 读取每一行数据
int rowCount = sheet.LastRowNum;
for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)
{
IRow row = sheet.GetRow(i);
DataRow dataRow = dataTable.NewRow();
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null)
{
dataRow[j] = row.GetCell(j).ToString();
}
}
dataTable.Rows.Add(dataRow);
}
}
return dataTable;
}
}
```
示例2:写入Excel文件
```csharp
using System;
using System.Data;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
public class ExcelWriter
{
public void WriteExcel(DataTable dataTable, string filePath)
{
using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
IWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet("Sheet1");
// 写入表头
IRow headerRow = sheet.CreateRow(0);
for (int i = 0; i < dataTable.Columns.Count; i++)
{
headerRow.CreateCell(i).SetCellValue(dataTable.Columns[i].ColumnName);
}
// 写入数据
for (int i = 0; i < dataTable.Rows.Count; i++)
{
IRow row = sheet.CreateRow(i + 1);
for (int j = 0; j < dataTable.Columns.Count; j++)
{
row.CreateCell(j).SetCellValue(dataTable.Rows[i][j].ToString());
}
}
workbook.Write(fileStream);
}
}
}
```
这样,你就可以使用`ExcelReader`类的`ReadExcel`方法来读取Excel文件,用`ExcelWriter`类的`WriteExcel`方法来写入Excel文件。当然,需要在项目中引用NPOI库。
阅读全文