在vs開發軟件中通過nuget安裝npoi
//讀取excel表格數據,並判斷表頭是否符合要求 (電腦可不安裝office) public static void ReadExcel() { string filePath = @"C:\Users\Administrator\Desktop\as.xlsx"; FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read); List<IRow> rowlist = new List<IRow>(); //創建工作簿對象 XSSFWorkbook workbook = new XSSFWorkbook(fileStream); ISheet sheet = workbook.GetSheetAt(0);//獲取第一張表 for (int i = 0; i < sheet.LastRowNum; i++) { IRow row = sheet.GetRow(i); rowlist.Add(row); row = null; } IRow indexRow = rowlist[0]; rowlist.Remove(indexRow);//移除表頭,直接循環列表值 //循環表體每一行數據 for (int i = 0; i < rowlist.Count; i++) { //循環每一行中每個單元格數據 for (int j = 0; j < rowlist[i].Cells.Count; j++) { //判斷當前循環單元格數據是否符合要求 if (indexRow.GetCell(j).ToString().Contains("oid")) { Console.WriteLine(rowlist[i].GetCell(j).ToString()); } else if (indexRow.GetCell(j).ToString().Contains("卡卡西")) { Console.WriteLine(rowlist[i].GetCell(j).ToString()); } } } }
public static void ExportExcel() { IWorkbook workbook = new XSSFWorkbook(); ISheet sheetx = workbook.CreateSheet("郵件信息"); //第一個是列索引:1表示第二列單元格,第二個參數是表示單元格字符數 30 * 256 表示該單元格可存儲30個字符 sheetx.SetColumnWidth(1, 15 * 256); IRow row1 = sheetx.CreateRow(0); row1.CreateCell(0).SetCellValue("用戶郵件信息"); //row1.Height = 50 * 10; IRow rowx0 = sheetx.CreateRow(1); List<EmailModel> list = EmailDal.GetModelList("","emailId,UserId"); rowx0.CreateCell(0).SetCellValue("郵件ID"); rowx0.CreateCell(1).SetCellValue("用戶ID"); rowx0.Height = 30 * 10; XSSFCellStyle fCellStyle = (XSSFCellStyle)workbook.CreateCellStyle(); XSSFFont ffont = (XSSFFont)workbook.CreateFont(); //給字體設置顏色 ffont.Color = HSSFColor.Red.Index; //給樣式添加字體 fCellStyle.SetFont(ffont); for (int i = 0; i < list.Count; i++) { IRow rowdata = sheetx.CreateRow(i + 2); rowdata.CreateCell(0).SetCellValue(list[i].emailId); rowdata.Height = 30 * 10; rowdata.GetCell(0).CellStyle = fCellStyle; rowdata.CreateCell(1).SetCellValue(list[i].UserId.ToString()); } var filePath = ""; var fileName = Guid.NewGuid() + "-用戶郵件表";
//如果是web,則注釋該行代碼 filePath = @"C:\Users\Administrator\Desktop\" + fileName + ".xlsx"; using (FileStream url = File.OpenWrite(filePath)) { workbook.Write(url); };
MemoryStream ms = new MemoryStream();
workbook.Write(ms);
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xlsx", fileName));
Response.BinaryWrite(ms.ToArray());
Response.End();
workbook = null;
ms.Close();
ms.Dispose();
}
通過讀取excel表格來判斷表頭數據
NPOI安裝dll文件下載:
鏈接:https://pan.baidu.com/s/1QiRVGsjr5qoLkgv64VfOKQ
提取碼:oguw