private void button2_Click(object sender, EventArgs e) { string file = textBox1.Text; string result = ""; DataTable dt = new DataTable(); ExcelResultEntity excel = new ExcelResultEntity(); int iprojectId; try { iprojectId = Convert.ToInt32(comboBox1.SelectedValue.ToString()); TokenResultEntity getToken = provide.GetToken(); if (getToken.Code != 0) { MessageBox.Show("获取Token失败, 错误信息: " + getToken.ErrMsg); return; } using (ExcelHelper excelHelper = new ExcelHelper(file)) { excel = excelHelper.GetExcelAttribute(); if (excel.Code != 0 || excel.SheetNumber == 0) { MessageBox.Show("Excel 异常请核对!"); return; } foreach (SheetName item in excel.SheetName) { dt = excelHelper.ExcelToDataTable(item.Name, true, 1); if (dt == null || dt.Rows.Count <= 1) { MessageBox.Show("Excel sheet名称: " + item.Name + "数据为空!"); return; } else { result = provide.ImportHouseInfo(dt, iprojectId, item.Name); if (!string.IsNullOrEmpty(result)) { MessageBox.Show("导入房源信息失败, 错误信息: " + result); return; } } } MessageBox.Show("导入房源信息成功!"); } } catch (Exception ex) { Console.WriteLine("Exception: " + ex.Message); } }
public ExcelResultEntity GetExcelAttribute() { ExcelResultEntity excelresult = new ExcelResultEntity(); int cnt; 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); } excelresult.SheetNumber = workbook.NumberOfSheets; for (cnt = 0; cnt < excelresult.SheetNumber; cnt++) { SheetName sn = new SheetName(); sn.Name = workbook.GetSheetAt(cnt).SheetName; excelresult.SheetName.Add(sn); } excelresult.Code = 0; excelresult.ErrMsg = ""; } catch (Exception ex) { excelresult.Code = 9999; excelresult.ErrMsg = "获取EXCEL属性异常: " + ex.Message; } return(excelresult); }