自动识别EXCEL2003和2007
引用句NPOI.dll、NPOI.OOXML.dll和NPOI.OpenXml4Net.dll
using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read))
{
IWorkbook hssfworkbook = NPOI.SS.UserModel.WorkbookFactory.Create(file);
}
这样就可以自动识别,好强大,以后终于不需要会EXCEL COM组件。
案例:
using (FileStream fs = File.OpenRead(openFileDialog.FileName))
{
IWorkbook wk = WorkbookFactory.Create(fs);//使用接口,自动识别excel2003/2007格式
ISheet sheet = wk.GetSheetAt(0);
for (int j = 0; j <= sheet.LastRowNum; j++) //LastRowNum 是当前表的总行数
{
if (ignoreRow == MaxIgnoreRow)
{
txtlog.AppendText("不符合规则的数据过多,退出,行号=" + (j + 1).ToString() + Environment.NewLine);
break;
}
if (nullRow == MaxIgnoreRow)
{
txtlog.AppendText("空行过多,提前退出" + Environment.NewLine);
break;
}
IRow row = sheet.GetRow(j); //读取当前行数据
if (row == null)
break;
ICell cell = row.GetCell(0); //当前表格
if (cell == null || string.IsNullOrWhiteSpace(cell.ToString().Trim()))
{
txtlog.AppendText("第" + (j + 1).ToString() + "行,第一单元格为空,继续下一行" + Environment.NewLine);
nullRow++;
continue;
}
try
{
barstr = cell.ToString().Trim();
if (!barReg.IsMatch(barstr))
{
//第1行的标题,本显示出错
if (j > 0)
{
txtlog.AppendText("第" + (j + 1).ToString() + "行,运单号:" + barstr + "不符合规则,请查证!" + Environment.NewLine);
ignoreRow++;
}
continue;
}
barImages.Add(bar.Encode(BarcodeLib.TYPE.CODE128C, barstr, Color.Black, Color.White, Settings.Default.BarcodeWidth, Settings.Default.BarcodeHeight));
}
catch (Exception ex2)
{
txtlog.AppendText("生成条码出错:" + ex2.Message + Environment.NewLine);
txtlog.AppendText("第" + (j + 1).ToString() + "行,运单号为:" + barstr + Environment.NewLine);
}
//每MaxCount个打印一次
if (barImages.Count == Settings.Default.MaxPrintCount)
pd.Print();
count++;
}
fs.Close();
}//using