最近做了一个从Excel读取数据进行标签打印的Demo,思路就是先将Excel数据读取到datatable里面,然后利用for循环打印出标签即可。方法如下:
IWorkbook iwkX;
//filePath excel地址 string filePath = "D:\2020.11.09.01.xlsx"; using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { iwkX = WorkbookFactory.Create(fs); fs.Close(); } //sheet DataTable dt = new DataTable(); for (int h = 0; h < iwkX.NumberOfSheets; h++) { ISheet sheet = iwkX.GetSheetAt(h); var rows = sheet.GetRowEnumerator(); bool isMove = rows.MoveNext(); //循环sheet if (isMove) { var Cols = (IRow)rows.Current; dt.TableName = sheet.SheetName; for (int i = 0; i < Cols.LastCellNum; i++) { string str = Cols.GetCell(i).ToString(); dt.Columns.Add(Cols.GetCell(i).ToString()); } while (rows.MoveNext()) { var row = (IRow)rows.Current; var dr = dt.NewRow(); for (int i = 0; i < row.LastCellNum; i++) { var cell = row.GetCell(i); if (cell == null) { dr[i] = ""; } else { string strdr = cell.ToString(); dr[i] = cell.ToString(); } } dt.Rows.Add(dr); } } }
return dt;
}
拿到datatable里的数据就好做了,剩下的就不演示了。