20

有人可以为我指出如何阅读 Excel 电子表格、遍历所有行和列以使用 EPPlus 和 MVC 检索值的正确方向吗?到目前为止,我看到了创建电子表格的示例,但在打开 excel 文件并从中读取值时没有找到任何示例。任何帮助,将不胜感激。

TIA 苏..

4

2 回答 2

23

简单的例子

// Get the file we are going to process
var existingFile = new FileInfo(filePath);
// Open and read the XlSX file.
using (var package = new ExcelPackage(existingFile))
{
    // Get the work book in the file
    var workBook = package.Workbook;
    if (workBook != null)
    {
        if (workBook.Worksheets.Count > 0)
        {
            // Get the first worksheet
            var currentWorksheet = workBook.Worksheets.First();

            // read some data
            object col1Header = currentWorksheet.Cells[1, 1].Value;
于 2012-07-29T07:58:35.893 回答
4

一个简单的例子,你可以在 .net 4.5 中使用 EPPlus 读取 excel 文件

public void readXLS(string FilePath)
{
    FileInfo existingFile = new FileInfo(FilePath);
    using (ExcelPackage package = new ExcelPackage(existingFile))
    {
        //get the first worksheet in the workbook
        ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
        int colCount = worksheet.Dimension.End.Column;  //get Column Count
        int rowCount = worksheet.Dimension.End.Row;     //get row count
        for (int row = 1; row <= rowCount; row++)
        {
            for (int col = 1; col <= colCount; col++)
            {
                Console.WriteLine(" Row:" + row + " column:" + col + " Value:" + worksheet.Cells[row, col].Value.ToString().Trim());
            }
        }
    }
}
于 2018-08-22T09:41:51.777 回答