一个通用的excel读取工具

xiaoxiao2021-02-28  60

package homework.excelutils; import java.io.File; import java.io.IOException; import java.util.List; import jxl.Sheet; import jxl.Workbook; import jxl.read.biff.BiffException; public class ExcelUtils { public static <T> List<T> read(File file, CallBack<T> call) { Workbook workbook = null; try { workbook = Workbook.getWorkbook(file); Sheet sheet = workbook.getSheet(0); return call.getDatas(sheet); } catch (BiffException e) { e.printStackTrace(); } catch (IndexOutOfBoundsException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } public interface CallBack<T> { public List<T> getDatas(Sheet sheet); } } //举个栗子 public void writeproduct() { List<Product> list = ExcelUtils.read(new File("商品表.xls"), new CallBack<Product>() { @Override public List<Product> getDatas(Sheet sheet) { List<Product> lp = new ArrayList<>(); int rows = sheet.getRows(); Product pro = null; SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); for (int i = 1; i < rows; i++) { String id = sheet.getCell(0,i).getContents(); String name = sheet.getCell(1,i).getContents(); String price = sheet.getCell(2,i).getContents(); String offset = sheet.getCell(3,i).getContents(); Date time = null; try { time = sdf.parse(sheet.getCell(4,i).getContents()); } catch (ParseException e) { e.printStackTrace(); } String counts = sheet.getCell(5,i).getContents(); String cid = sheet.getCell(6,i).getContents(); pro = new Product(Integer.parseInt(id), name, Double.parseDouble(price),Double.parseDouble(offset), time, Integer.parseInt(counts),Integer.parseInt(cid)); lp.add(pro); } return lp; } }); ProductDAO p = new ProductDAO(); for (Product product : list) { p.insert(product); } }
转载请注明原文地址: https://www.6miu.com/read-71885.html

最新回复(0)