MultipartFile上传csv和excel文件保存到数据库中

时间:2025-02-15 18:19:12
  • public class ExportExcelFile {
  • private static final String EXCEL_XLS = "xls";
  • private static final String EXCEL_XLSX = "xlsx";
  • //判断版本获取Wordboook
  • private static Workbook getWorkbook(InputStream in, String fileName) throws IOException {
  • Workbook wbook = null;
  • if ((EXCEL_XLS)) {
  • wbook = new HSSFWorkbook(in);
  • } else if ((EXCEL_XLSX)) {
  • wbook = new XSSFWorkbook(in);
  • }
  • return wbook;
  • }
  • //解析excel文件问对象集合
  • public static List<T> getExcelData(MultipartFile mfile, String fileName) {
  • List<List<String>> lists = new ArrayList<List<String>>();
  • try {
  • Workbook workbook = getWorkbook((), fileName);
  • //获取Sheet的数量
  • int sheetCount = ();
  • // 第一个Sheet
  • Sheet sheet = (0);
  • //表头
  • Row rowHead = (0);
  • //总列数
  • int columns = ();
  • //总行数
  • int lines = ();
  • //循环获取每行数据
  • for (int i = 0; i < lines; i++) {
  • //循环获取每列
  • List<String> list = new ArrayList<String>();
  • for (int j = 0; j < columns; j++) {
  • if ((i).getCell(j) != null){
  • Object obj = getValue((i).getCell(j));
  • ((obj));
  • }else {
  • (null);
  • }
  • }
  • (list);
  • }
  • }catch (FileNotFoundException e) {
  • ();
  • } catch (IOException e) {
  • ();
  • }
  • JSONArray array = toJsonArray(lists);
  • return ();
  • }
  • //获取对应的枚举类型数据
  • private static Object getValue(Cell cell) {
  • Object obj = null;
  • switch (()) {
  • case BOOLEAN:
  • obj = ();
  • break;
  • case ERROR:
  • obj = ();
  • break;
  • case NUMERIC:
  • obj = ();
  • break;
  • case STRING:
  • obj = ();
  • break;
  • default:
  • break;
  • }
  • return obj;
  • }