以前写了一篇excel导入数据到数据库的文章,是先将excel导入到datatable中在进行批量插入操作,实现数据的导入工作;最近在写一个上传数据服务时,发现有些许问题,在此予以更正,问题描述:
就会报异常:“The supplied data appears to be in the Office 2007+ XML. You are calling the part of POI that deals with OLE2 Office Documents. You need to call a different part of POI to process this data (eg XSSF instead of HSSF)”
/// <summary>
/// 将excel中的数据导入到DataTable中
/// </summary>
/// <param name="sheetName">excel工作薄sheet的名称</param>
/// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
/// <returns>返回的DataTable</returns>
public DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn, int startRow = 0)
{
ISheet sheet = null;
DataTable data = new DataTable();
try
{
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook(fs);
else if (fileName.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook(fs);
if (sheetName != null && sheetName != "")
{
sheet = workbook.GetSheet(sheetName);
if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
{
sheet = workbook.GetSheetAt(0);
}
}
else
{
sheet = workbook.GetSheetAt(0);
}
if (sheet != null)
{
IRow firstRow = sheet.GetRow(startRow);
int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
if (isFirstRowColumn)
{
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
ICell cell = firstRow.GetCell(i);
if (cell != null)
{
string cellValue = cell.Value().ToString();
if (cellValue != null)
{
DataColumn column = new DataColumn(cellValue);
data.Columns.Add(column);
}
}
}
if (startRow == 0)
{
startRow = sheet.FirstRowNum + 1;
}
else
{
startRow += 1;
}
}
else
{
if (startRow == 0)
{
startRow = sheet.FirstRowNum;
}
}
//最后一列的标号
int rowCount = sheet.LastRowNum;
for (int i = startRow; i <= rowCount; ++i)
{
IRow row = sheet.GetRow(i);
if (row == null || row.FirstCellNum < 0 || (row.GetCell(0).Value() == null || string.IsNullOrWhiteSpace(row.GetCell(0).Value().ToString()))) break; //没有数据的行默认是null
DataRow dataRow = data.NewRow();
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j).Value() != null) //同理,没有数据的单元格都默认是null
dataRow[j] = row.GetCell(j).Value().ToString();
else
dataRow[j] = string.Empty;
}
data.Rows.Add(dataRow);
}
}
return data;
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
return null;
}
}
上面的代码在excel没有标题和表头的时候是没有任何问题的,但是如果内容有表头就可能出现问题 ;报错的代码时红色标注的那行,加载2003时失败,看了下使用后缀名进行判断的;如果将2007的后缀名改成2003同样会出现这个问题;同时。2007能解析完整的表格数据结构,如下图:
错误的解析格式:
因为2003和2007中合并标题中,可能存在些许差异,使得为null值的单元格在添加列的时候不会被当做一列,添加的列数中,在解析式有些数据无法解析;因此鉴于以上原因我对代码进行了重新修改,内容如下:
/// <summary>
/// 将excel中的数据导入到DataTable中
/// </summary>
/// <param name="sheetName">excel工作薄sheet的名称</param>
/// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
/// <returns>返回的DataTable</returns>
public DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn, int startRow = 0)
{
ISheet sheet = null;
DataTable data = new DataTable();
try
{
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
//if (fileName.IndexOf(".xlsx") > 0) // 2007版本
// workbook = new XSSFWorkbook(fs);
//else if (fileName.IndexOf(".xls") > 0) // 2003版本
// workbook = new HSSFWorkbook(fs);
workbook = WorkbookFactory.Create(fs);
if (sheetName != null && sheetName != "")
{
sheet = workbook.GetSheet(sheetName);
if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
{
sheet = workbook.GetSheetAt(0);
}
}
else
{
sheet = workbook.GetSheetAt(0);
}
if (sheet != null)
{
IRow firstRow = sheet.GetRow(startRow);
int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
if (isFirstRowColumn)
{
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
ICell cell = firstRow.GetCell(i);
if (cell != null)
{
string cellValue = cell.Value().ToString();
if (cellValue != null)
{
DataColumn column = new DataColumn(cellValue);
data.Columns.Add(column);
}
}
else
{
DataColumn column = new DataColumn(string.Empty);
data.Columns.Add(column);
}
}
if (startRow == 0)
{
startRow = sheet.FirstRowNum + 1;
}
else
{
startRow += 1;
}
}
else
{
if (startRow == 0)
{
startRow = sheet.FirstRowNum;
}
}
//最后一列的标号
int rowCount = sheet.LastRowNum;
for (int i = startRow; i <= rowCount; ++i)
{
IRow row = sheet.GetRow(i);
if (row == null || row.FirstCellNum < 0 || (row.GetCell(0).Value() == null || string.IsNullOrWhiteSpace(row.GetCell(0).Value().ToString()))) break; //没有数据的行默认是null
DataRow dataRow = data.NewRow();
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j).Value() != null) //同理,没有数据的单元格都默认是null
dataRow[j] = row.GetCell(j).Value().ToString();
else
dataRow[j] = string.Empty;
}
data.Rows.Add(dataRow);
}
}
return data;
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
return null;
}
}
说明:
1.利用WorkbookFactory.Create(inputStream)自动识别excel的格式;避免格式问题引发的异常;
2.对于有表头的数据列进行适配,确保所有的列计算在内,这样数据在进行转换时就不会出现越界错误。
下面是WorkbookFactory.Create(inputStream)的源码,有兴趣额的可以学习一下:
/**
* Creates the appropriate HSSFWorkbook / XSSFWorkbook from
* the given InputStream.
* Your input stream MUST either support mark/reset, or
* be wrapped as a {@link PushbackInputStream}!
*/
public static Workbook create(InputStream inp) throws IOException, InvalidFormatException {
// If clearly doesn't do mark/reset, wrap up
if(! inp.markSupported()) {
inp = new PushbackInputStream(inp, 8);
}
if(POIFSFileSystem.hasPOIFSHeader(inp)) {
return new HSSFWorkbook(inp);
}
if(POIXMLDocument.hasOOXMLHeader(inp)) {
return new XSSFWorkbook(OPCPackage.open(inp));
}
throw new IllegalArgumentException("Your InputStream was neither an OLE2 stream, nor an OOXML stream");
}