zoukankan      html  css  js  c++  java
  • C#--上文Excel文件数据获取

    Excel文件上传,后台初次认定的只是个有大小的文件流,要想获取上传的数据,则需要用到NPOl

    获取文件流

    1 HttpPostedFileBase filebase=Request.Files[0]; //单独文件访问
    2 Stream inputstream=filebase.InputStream; //获取excel文档流
    3 string filename=filebase.FileName;
    View Code

    Excel文件流转换成datatable

     1    IWorkbook workbook = new XSSFWorkbook(filestream); //.xlsx
     2    ISheet sheet=workbook.GetSheetAt(0); 
     3 
     4     DataTable table = new DataTable();
     5 
     6             IRow headerRow = sheet.GetRow(headerRowIndex);
     7 
     8             if (headerRow == null) return table;
     9 
    10             int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells
    11             int rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1
    12 
    13             //handling header(处理标题).
    14             for (int i = headerRow.FirstCellNum; i < cellCount; i++)
    15             {
    16                 string headColumnName = GetCellValue(headerRow.GetCell(i));  //GetCellValue()根据Excel列类型获取列的值
    17 
    18                 while (table.Columns.Contains(headColumnName)) headColumnName = headColumnName + "+";
    19 
    20                 DataColumn column = new DataColumn(headColumnName);
    21                 table.Columns.Add(column);
    22 
    23             }
    24             for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)
    25             {
    26                 IRow row = sheet.GetRow(i);
    27                 DataRow dataRow = table.NewRow();
    28                 if (row != null && row.FirstCellNum > -1)
    29                 {
    30                     for (int j = row.FirstCellNum; j < cellCount; j++)
    31                     {
    32                         if (row.GetCell(j) != null)
    33                         {
    34                             if (dataRow.ItemArray.Length > j)
    35                             {
    36                                 dataRow[j] = GetCellValue(row.GetCell(j));
    37                             }
    38                         }
    39                     }
    40                     table.Rows.Add(dataRow);
    41                 }
    42             }
    43             return table;
    View Code
  • 相关阅读:
    [JS]手写动画最小时间间隔设置
    [CSS3]chrome浏览器中支持汉字的最小像素是12px,如何让显示更小的字体
    [HTML,CSS]div+css垂直水平居中
    promise经典题目
    HTML5新兴API
    使用MessageChannel(消息通道)进行深拷贝
    原生js手写Promise
    github图片显示不出来-已解决
    前端原生js加密解密
    vue-cli3前端工程静态文件下载
  • 原文地址:https://www.cnblogs.com/leap-li/p/7737621.html
Copyright © 2011-2022 走看看