网上查阅了一些数据,但是很多代码不全,或者存在一些bug,以及有些数据内容写死,不方便多种场合使用,以下,做了一个简单的封装满足一些简单功能的操作。(前端只需要传递给后台所需要的参数就可以实现以下功能)
公用的部分:
下面功能的实现,需要导入3个jar包,主要是poi的包(详情请看备注)
实体类:
为了调用方便,我又添加了两个getString和setString的方法,主要是用来方便后面代码的调用(只需要知道是第几列即可,方便对列进行遍历)
package cn.coco.entity; public class PageData { private String stuName; private String stuSex; private String stuAge; private String stuSchoolName; private String stuClassName; public String getStuName() { return stuName; } public void setStuName(String stuName) { this.stuName = stuName; } public String getStuSex() { return stuSex; } public void setStuSex(String stuSex) { this.stuSex = stuSex; } public String getStuAge() { return stuAge; } public void setStuAge(String stuAge) { this.stuAge = stuAge; } public String getStuSchoolName() { return stuSchoolName; } public void setStuSchoolName(String stuSchoolName) { this.stuSchoolName = stuSchoolName; } public String getStuClassName() { return stuClassName; } public void setStuClassName(String stuClassName) { this.stuClassName = stuClassName; } @Override public String toString() { return "PageData [stuName=" + stuName + ", stuSex=" + stuSex + ", stuAge=" + stuAge + ", stuSchoolName=" + stuSchoolName + ", stuClassName=" + stuClassName + "]"; } public void setString(String str,int j){ if(j<0){ System.out.println("列数的起始下标必须大于等于0!"); return; } //此处需要注意title内容与列数相匹配 switch (j) { case 0:setStuName(str); break; case 1:setStuSex(str); break; case 2:setStuAge(str); break; case 3:setStuSchoolName(str); break; case 4:setStuClassName(str); break; default: break; } } public String getString(int j){ String str=""; //此处需要注意title内容与列数相匹配 switch (j) { case 0: str = getStuName(); break; case 1: str = getStuSex(); break; case 2: str = getStuAge(); break; case 3: str = getStuSchoolName(); break; case 4: str = getStuClassName(); break; default: break; } return str; } }
简单封装的工具类:
package cn.coco.util; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; public class ExcelUtil { /** * 导出Excel * @param sheetName sheet名称 * @param title 标题 * @param values 内容 * @param wb HSSFWorkbook对象 * @return */ public static HSSFWorkbook getHSSFWorkbook(String sheetName,String []title,String [][]values, HSSFWorkbook wb){ // 第一步,创建一个HSSFWorkbook,对应一个Excel文件 if(wb == null){ wb = new HSSFWorkbook(); } // 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet HSSFSheet sheet = wb.createSheet(sheetName); // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制 HSSFRow row = sheet.createRow(0); // 第四步,创建单元格,并设置值表头 设置表头居中 HSSFCellStyle style = wb.createCellStyle(); // style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式 //声明列对象 HSSFCell cell = null; //创建标题 for(int i=0;i<title.length;i++){ cell = row.createCell(i); cell.setCellValue(title[i]); cell.setCellStyle(style); } //创建内容 for(int i=0;i<values.length;i++){ row = sheet.createRow(i + 1); for(int j=0;j<values[i].length;j++){ //将内容按顺序赋给对应的列对象 row.createCell(j).setCellValue(values[i][j]); } } return wb; } }
功能一:将数据处理,导出并保存到指定目录下面
/** * 将数据装换为Excel文件的形式 */ private static HSSFWorkbook writeToExcel(List list,String[] title,String sheetName){ //excel文件名 String fileName = sheetName+System.currentTimeMillis()+".xls"; System.out.println("fileName"+fileName); String[][] content =new String[list.size()][title.length]; System.out.println("list.size()"+list.size()+"||"+"title.length"+title.length); for (int i = 0; i < list.size(); i++) { content[i] = new String[title.length]; PageData obj = (PageData)list.get(i); for(int j=0;j<title.length;j++){ content[i][j] = obj.getString(j); } } //创建HSSFWorkbook HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null); return wb; } /** * 保存Excel文件导致指定位置 */ private static boolean saveExcel(String path,HSSFWorkbook wb){ try { OutputStream outputStream = new FileOutputStream(path); wb.write(outputStream); outputStream.close(); } catch (Exception e) { e.printStackTrace(); return false; } return true; }
功能二:读取指定位置下面的Excel文件内容:
/** * 读取Excel * * @return 数据集合 */ private static List<PageData> readExcel(String path) { List<PageData> list = new ArrayList<PageData>(); HSSFWorkbook workbook = null; try { // 读取Excel文件 InputStream inputStream = new FileInputStream(path); workbook = new HSSFWorkbook(inputStream); inputStream.close(); } catch (Exception e) { e.printStackTrace(); } // 循环工作表 for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) { HSSFSheet hssfSheet = workbook.getSheetAt(numSheet); if (hssfSheet == null) { continue; } // 循环行 for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) { HSSFRow hssfRow = hssfSheet.getRow(rowNum); int columnNum=hssfRow.getPhysicalNumberOfCells(); System.out.println("该表格的行数有:"+hssfSheet.getLastRowNum()+"行"+columnNum+"列"); if (hssfRow == null) { continue; } // 将单元格中的内容存入集合 HSSFCell cell; PageData student = new PageData(); for(int j=0;j<columnNum;j++){ cell = hssfRow.getCell(j); if (cell == null) { continue; } String str = cell.getStringCellValue(); student.setString(str,j); } list.add(student); } } return list; }
注释:如果实体类没有加getString和setString方法,那么就需要:
// HSSFCell cell = hssfRow.getCell(0); // if (cell == null) { // continue; // } // student.setStuName(cell.getStringCellValue()); // // cell = hssfRow.getCell(1); // if (cell == null) { // continue; // } // // student.setStuSex(cell.getNumericCellValue()+""); // student.setStuSex(cell.getStringCellValue()); // // cell = hssfRow.getCell(2); // if (cell == null) { // continue; // } // student.setStuAge(cell.getStringCellValue()); // // cell = hssfRow.getCell(3); // if (cell == null) { // continue; // } // student.setStuSchoolName(cell.getStringCellValue()); // // cell = hssfRow.getCell(4); // if (cell == null) { // continue; // } // student.setStuClassName(cell.getStringCellValue());
但是修改之后:可以简化为:
HSSFCell cell; PageData student = new PageData(); for(int j=0;j<columnNum;j++){ cell = hssfRow.getCell(j); if (cell == null) { continue; } String str = cell.getStringCellValue(); student.setString(str,j); } list.add(student);
下面就是简单测试的demo:
public static void main(String[] args){ //模拟参数++++++++++++++++++++++++++++++++++++++++++++++ //获取数据 List<PageData> list =new ArrayList<>(); for(int i=0;i<3;i++){ PageData e = new PageData(); e.setStuAge("1"+i); e.setStuClassName("0"+i); e.setStuName("xues"+i); e.setStuSchoolName(""+i); e.setStuSex(""); list.add(e); } //excel标题 String[] title = {"名称","性别","年龄","学校","班级"}; //sheet名 String sheetName = "学生信息表"; // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //将数据装换为Excel文件的形式 HSSFWorkbook wb= writeToExcel(list,title,sheetName); //将生成的Excel保存到指定位置 String path ="D:/students.xls"; saveExcel(path,wb); //读取指定位置下面的Excel文件内容 List<PageData> li =readExcel(path); for(int i=0;i<li.size();i++){ System.out.println("li=================================="+li.get(i)); } }
测试结果:
备注:上述代码需要导包:
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
以及一些常用的io用到的包,见网址:(目前是最新版本,支持jdk6,)
https://download.csdn.net/download/yaoy1016/10360242