功能很简单,点击按钮,弹出对话框,选择xls文件,用NOPI插件读件excel文件显示到datagridview中,但现在点击选择文件后,就抛异常,哪位大师看下
这是按钮代码:
private void button1_Click(object sender, EventArgs e)
{
string name = null ;
OpenFileDialog filename = new OpenFileDialog();
filename.InitialDirectory = Application.StartupPath;
filename.Filter = “All files(*.*)|*.*|xls files(*.xls)|*.xlsx”;
filename.FilterIndex = 2;
filename.RestoreDirectory = true;
if (filename.ShowDialog() == DialogResult.OK)
{
name = filename.FileName.ToString();
//string name=path.Substring.(path.LastIndexOf(“\”)+1);
}
//MessageBox.Show(name);
//ExcelHelper biao = new ExcelHelper();
DataTable dt = new DataTable();
dt = ExcelHelper.ExcelToDataTable(name, 0);
dgv_one.DataSource = dt;
下面是功能代码:
public static DataTable ExcelToDataTable(string strFileName, int sheetIndex = 0)
{
DataTable dt = new DataTable();
HSSFWorkbook hssfworkbook = null;
XSSFWorkbook xssfworkbook = null;
string fileExt = Path.GetExtension(strFileName);//获取文件的后缀名
using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
{
if (fileExt == “.xls”)
hssfworkbook = new HSSFWorkbook(file); //抛异常,未处理IOexception Invalid header signature; read 0x0003001C171C7D84, expected 0xE11AB1A1E011CFD0
else if (fileExt == “.xlsx”)
xssfworkbook = new XSSFWorkbook(file);//初始化太慢了,不知道这是什么bug 抛异常,未处理Zipexception Wrong Local header signature: 0xD71C7D84
}
if (hssfworkbook != null)
{
HSSFSheet sheet = (HSSFSheet)hssfworkbook.GetSheetAt(sheetIndex);
if (sheet != null)
{
System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
HSSFRow headerRow = (HSSFRow)sheet.GetRow(0);
int cellCount = headerRow.LastCellNum;
for (int j = 0; j < cellCount; j++)
{
HSSFCell cell = (HSSFCell)headerRow.GetCell(j);
dt.Columns.Add(cell.ToString());
}
for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
{
HSSFRow row = (HSSFRow)sheet.GetRow(i);
DataRow dataRow = dt.NewRow();
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null)
dataRow[j] = row.GetCell(j).ToString();
}
dt.Rows.Add(dataRow);
}
}
异常:
