1. 程式人生 > >ASP.Net MVC利用NPOI匯入匯出Excel

ASP.Net MVC利用NPOI匯入匯出Excel

原文連結

因近期專案遇到所以記錄一下:

首先匯出Excel :

首先引用NPOI包

(Action一定要用FileResult)

/// <summary>/// 批量匯出本校第一批派位學生/// </summary>/// <returns></returns>public FileResult ExportStu2()
    {
     
string schoolname = "401";
     
//建立Excel檔案的物件
      NPOI.HSSF.UserModel.HSSFWorkbookbook =
newNPOI.HSSF.UserModel.HSSFWorkbook();
     

//新增一個sheet
      NPOI.SS.UserModel.ISheet sheet1 =book.CreateSheet(
"Sheet1");
     
//獲取list資料
      List<TB_STUDENTINFOModel>listRainInfo =
m_BLL.GetSchoolListAATQ(schoolname);
     
//給sheet1新增第一行的頭部標題
      NPOI.SS.UserModel.IRow row1 =sheet1.CreateRow(
0);
      row1.CreateCell(
0).SetCellValue("電腦號"
);
      row1.CreateCell(
1).SetCellValue("姓名");
     
//將資料逐步寫入sheet1各個行for (int i= 0; i < listRainInfo.Count; i++)
      {
        NPOI.SS.UserModel.IRow rowtemp
= sheet1.CreateRow(i + 1);
        rowtemp.CreateCell(
0).SetCellValue(listRainInfo[i].ST_CODE.ToString());
        rowtemp.CreateCell(
1).SetCellValue(listRainInfo[i].ST_NAME.ToString());
      }
     
// 寫入到客戶端
      System.IO.MemoryStream ms =
new System.IO.MemoryStream();
      book.Write(ms);
      ms.Seek(
0, SeekOrigin.Begin);
     
return File(ms, "application/vnd.ms-excel", "第一批電腦派位生名冊.xls");
    }

前臺直接寫就可實現:

1、  @Html.ActionLink("點選匯出名冊", "ExportStu2")

下面說一下匯出:

首先說一些前臺吧,mvc上傳注意必須加 new{ enctype = "multipart/form-data" }:

<td>2、@using(@Html.BeginForm("ImportStu", "ProSchool", FormMethod.Post, new { enctype = "multipart/form-data" }))
                        {
                       
<text>選擇上傳檔案:(工作表名為“Sheet1”,“電腦號”在A1單元格。)</text><input name="file" type="file"id="file" /><input type="submit" name="Upload" value="批量匯入第一批電腦派位名冊" />
                        }
                   
</td>

後臺實現:只傳路徑得出DataTable:

/// <summary>/// Excel匯入/// </summary>/// <paramname="filePath"></param>/// <returns></returns>public DataTable ImportExcelFile(string filePath)
    {
      HSSFWorkbookhssfworkbook;
     
#region//初始化資訊try
      {
       
using (FileStream file = new FileStream(filePath, FileMode.Open,FileAccess.Read))
        {
          hssfworkbook
= new HSSFWorkbook(file);
        }
      }
     
catch (Exception e)
      {
       
throw e;
      }
     
#endregion

using (NPOI.SS.UserModel.ISheet sheet =hssfworkbook.GetSheetAt(0))
      {
        DataTable table
= new DataTable();
        IRow headerRow
= sheet.GetRow(0);//第一行為標題行int cellCount = headerRow.LastCellNum;//LastCellNum =PhysicalNumberOfCellsint rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1

//handling header.for (int i= headerRow.FirstCellNum; i < cellCount; i++)
        {
          DataColumn column
= newDataColumn(headerRow.GetCell(i).StringCellValue);
         table.Columns.Add(column);
        }
       
for (int i= (sheet.FirstRowNum + 1); i <= rowCount; i++)
        {
          IRow row
= sheet.GetRow(i);
          DataRow dataRow
= table.NewRow();

if (row != null)
          {
           
for (int j = row.FirstCellNum; j < cellCount; j++)
            {
             
if (row.GetCell(j) != null)
                dataRow[j]
= GetCellValue(row.GetCell(j));
            }
          }

table.Rows.Add(dataRow);
        }
       
return table;
      }
     
    }

補充一個類

/// <summary>/// 根據Excel列型別獲取列的值/// </summary>/// <param name="cell">Excel列</param>/// <returns></returns>private static string GetCellValue(ICell cell)
    {
     
if (cell == null)
       
return string.Empty;
     
switch (cell.CellType)
      {
       
case CellType.BLANK:
         
return string.Empty;
       
case CellType.BOOLEAN:
         
return cell.BooleanCellValue.ToString();
       
case CellType.ERROR:
         
return cell.ErrorCellValue.ToString();
       
case CellType.NUMERIC:
       
case CellType.Unknown:
       
default:
         
return cell.ToString();//This is a trick to get the correct value of thecell. NumericCellValue will return a numeric value no matter the cell value isa date or a numbercase CellType.STRING:
         
return cell.StringCellValue;
       
case CellType.FORMULA:
         
try
          {
            HSSFFormulaEvaluator e
= new HSSFFormulaEvaluator(cell.Sheet.Workbook);
           e.EvaluateInCell(cell);
           
return cell.ToString();
          }
         
catch
          {
           
returncell.NumericCellValue.ToString();
          }
      }
    }

得到DataTable後,就想怎麼操作就怎麼操作了