NPOI excel模板导入到数据库代码

          public List<T> ImportExe()
          {
              try
              {
                  OpenFileDialog ofd = new OpenFileDialog();
                  ofd.Title = "Excel文件"; ofd.FileName = "";
                  ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                  ofd.Filter = "所有文件(*.*)|*.*|Excel2003文件(*.xls)|*.xls|Excel2007文件(*.xlsx)|*.xlsx";
                  ofd.ValidateNames = true;
                  ofd.CheckFileExists = true;
                  ofd.CheckPathExists = true;
                  string file = string.Empty;
                  if (ofd.ShowDialog() == DialogResult.OK)
                  { file = ofd.FileName; }
                  if (file == "")
                  { XtraMessageBox.Show("没有选择Excel文件!无法进行数据导入"); }
                  else
                  {
                      List<string> dataList = new List<string>();
                      IWorkbook workbook;
                      string fileExt = Path.GetExtension(file).ToLower();
                      using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
                      {
                          //根据不同版本 
                          if (fileExt == ".xlsx")//2007版本 
                          {
                              workbook = new XSSFWorkbook(fs);
                          }
                          else if (fileExt == ".xls")//2003版本 
                          {
                              workbook = new HSSFWorkbook(fs);
                          }
                          else
                          {
                              workbook = null;
                          }
                          //获取第一个sheet页内容 
                          ISheet sheet = workbook.GetSheetAt(0);
                          int count = workbook.NumberOfSheets;//获取sheet页总数量 
                          for (int z = 0; z < count; z++)
                          {
                              DataTable dt = new DataTable();
                              dt.TableName = sheet.SheetName;
                              sheet = workbook.GetSheetAt(z);
                              //表头 
                              IRow header = sheet.GetRow(sheet.FirstRowNum);
                              if (header == null) continue;
                              List<int> columns = new List<int>();
                              for (int i = 0; i < header.LastCellNum; i++)
                              {
                                  columns.Add(i);
                                  ICell a = header.GetCell(i);//列名 
                                  DataColumn dc = new DataColumn(a.ToString(), typeof(string));
                                  dt.Columns.Add(dc);
                              }
                              //数据值 
                              for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum - 1; i++)
                              {
                                  DataRow dr = dt.NewRow();
                                  foreach (int j in columns)
                                  {
                                      if (sheet.GetRow(i) != null)
                                          dr[j] = sheet.GetRow(i).GetCell(j);
                                  }
                                  dt.Rows.Add(dr);
                              }
                              List<T> list = ConvertViewModel(dt);
                              if (list == null)
                              {
                                  XtraMessageBox.Show("没有导入的数据,请检查表格里的数据格式是否正确");
                                  return null;
                              }
                              return list;
                          }
                      }
                  }
                  return null;
              }
              catch (Exception ex)
              {
                  XtraMessageBox.Show($"{ex}");
                  return null;
              }
          }


    public List<T> ConvertViewModel(DataTable dt)
    {
        List<T> items = new List<T>();
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            if (dt.Rows[i]["题型"] == null || dt.Rows[i]["题目内容"] == null || dt.Rows[i]["答案"] == null)
            {
                XtraMessageBox.Show("题型或者题目内容或者答案不能为空");
                return null;
            }
            T item = new T();
            item.answer = dt.Rows[i]["答案"].ToString().Trim();
            item.option1 = dt.Rows[i]["选项1"].ToString().Trim();
            item.option2 = dt.Rows[i]["选项2"].ToString().Trim();
            item.option3 = dt.Rows[i]["选项3"].ToString().Trim();
            item.option4 = dt.Rows[i]["选项4"].ToString().Trim();
            item.option5 = dt.Rows[i]["选项5"].ToString().Trim();
            item.question_content = dt.Rows[i]["题目内容"].ToString().Trim()?.Replace("_____","(   )");
            item.question_type = GetQuestiontype(dt.Rows[i]["题型"].ToString().Trim());
            items.Add(item);
        }
        return items;
    }
posted @ 2022-01-11 11:20  泽哥的学习笔记  阅读(207)  评论(0编辑  收藏  举报