从64位版本服务器中的C#读取Excel文件,可以使用以下方法:
using Microsoft.Office.Interop.Excel;
public void ReadExcelFile(string filePath)
{
Application app = new Application();
Workbook workbook = app.Workbooks.Open(filePath);
Worksheet worksheet = workbook.Sheets[1];
Range range = worksheet.UsedRange;
object[,] values = range.Value2;
// 遍历values数组,获取Excel中的数据
for (int i = 1; i <= values.GetLength(0); i++)
{
for (int j = 1; j <= values.GetLength(1); j++)
{
Console.WriteLine(values[i, j]);
}
}
workbook.Close();
app.Quit();
}
例如,使用EPPlus库可以这样操作:
using OfficeOpenXml;
public void ReadExcelFile(string filePath)
{
using (ExcelPackage package = new ExcelPackage(new FileInfo(filePath)))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
for (int row = 1; row <= worksheet.Dimension.End.Row; row++)
{
for (int col = 1; col <= worksheet.Dimension.End.Column; col++)
{
Console.WriteLine(worksheet.Cells[row, col].Value);
}
}
}
}
无论使用哪种方法,都需要注意以下几点:
领取专属 10元无门槛券
手把手带您无忧上云