1. Java uses POI to import and export Excel tables demo
1.Introduce dependencies
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency>
2.Import demo
2.1 controller layer
/** * Excel导入 */ @PostMapping("/import") public Result userImport2(@RequestParam("file") MultipartFile file) throws Exception{ Result result=userService.userImportExcel(file); return result; }
2.2 service implementation class layer
public Result userImportExcel(MultipartFile file){ try { InputStream inputStream = file.getInputStream(); XSSFWorkbook sheets = new XSSFWorkbook(inputStream); //获取表单sheet 第一个 XSSFSheet sheetAt = sheets.getSheetAt(0); //获取第一行 int firstRowNum = sheetAt.getFirstRowNum(); //最后一行 int lastRowNum = sheetAt.getLastRowNum(); //存入数据集合 List<User> users=new ArrayList<>(); //遍历数据 for(int i=firstRowNum+1;i<lastRowNum+1;i++){ XSSFRow row = sheetAt.getRow(i); if(row!=null){ /* //获取第一行的第一列 int firstCellNum = row.getFirstCellNum(); //获取第一行的最后列 short lastCellNum = row.getLastCellNum(); for (int j=firstCellNum;j<lastCellNum+1;j++){ //放入集合中需要可以用这种方法 String cellValue = getValue(row.getCell(firstCellNum)); }*/ //这里我就直接赋值 User user = new User(); user.setUname(row.getCell(0).getStringCellValue()); user.setUpassword(row.getCell(1).getStringCellValue()); user.setUsex(row.getCell(2).getStringCellValue()); user.setRole(row.getCell(3).getStringCellValue()); user.setUlove((int) row.getCell(4).getNumericCellValue()); user.setUphoto(row.getCell(5).getStringCellValue()); user.setUaddress(row.getCell(6).getStringCellValue()); users.add(user); } } //保存数据 saveBatch(users); return Result.success(); }catch (Exception e){ e.printStackTrace(); log.info("error:{}",e); } return Result.error("300","导入失败"); } /** * 判断值的类型 */ public String getValue(HSSFCell cell) { if(cell==null){ return ""; } String cellValue= ""; try { DecimalFormat df=new DecimalFormat("0.00"); if(cell.getCellType()== CellType.NUMERIC){ //日期时间转换 if(HSSFDateUtil.isCellDateFormatted(cell)){ cellValue=DateFormatUtils.format(cell.getDateCellValue(),"yyyy-MM-dd"); }else{ NumberFormat instance = NumberFormat.getInstance(); cellValue=instance.format(cell.getNumericCellValue()).replace(",",""); } }else if(cell.getCellType() == CellType.STRING){ //字符串 cellValue=cell.getStringCellValue(); }else if(cell.getCellType() == CellType.BOOLEAN){ //Boolean cellValue= String.valueOf(cell.getBooleanCellValue()); }else if(cell.getCellType() == CellType.ERROR){ //错误 }else if(cell.getCellType() == CellType.FORMULA){ //转换公式 保留两位 cellValue=df.format(cell.getNumericCellValue()); }else{ cellValue=null; } } catch (Exception e) { e.printStackTrace(); cellValue="-1"; } return cellValue; }
3. Export demo
3.1 controller layer
/** * 导出 * @param response * @return * @throws Exception */ @GetMapping("/export") public Result userExport2(HttpServletResponse response) throws Exception{ Result result=userService.userExportExcel(response); return result; }
3.2 service implementation class
public Result userExportExcel(HttpServletResponse response) { try { //创建excel XSSFWorkbook sheets = new XSSFWorkbook(); //创建行 XSSFSheet sheet = sheets.createSheet("用户信息"); //格式设置 XSSFCellStyle cellStyle = sheets.createCellStyle(); //横向居中 cellStyle.setAlignment(HorizontalAlignment.CENTER); //创建单元格第一列 XSSFRow row = sheet.createRow(0); //表头 this.titleExcel(row,cellStyle); //查询全部的用户数据 mybatis-plus List<User> list = list(); //遍历设置值 for(int i=0;i<list.size();i++){ XSSFRow rows = sheet.createRow(i+1); User user=list.get(i); //表格里赋值 this.titleExcelValue(user,rows,cellStyle); } //设置浏览器响应格式 response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"); String filName= URLEncoder.encode("用户信息","UTF-8"); response.setHeader("Content-Disposition","attachment;filename="+filName+".xls"); ServletOutputStream outputStream=response.getOutputStream(); sheets.write(outputStream); outputStream.close(); sheets.close(); return Result.success(); }catch (Exception e){ e.printStackTrace(); log.info("error:{}",e); } return Result.error("300","导出失败"); } /** *表格里赋值 **/ public void titleExcelValue(User user, XSSFRow row,XSSFCellStyle cellStyle) { XSSFCell cellId = row.createCell(0); cellId.setCellValue(user.getUid()); cellId.setCellStyle(cellStyle); XSSFCell cellUserName = row.createCell(1); cellUserName.setCellValue(user.getUname()); cellUserName.setCellStyle(cellStyle); XSSFCell cellPassword = row.createCell(2); cellPassword.setCellValue(user.getUpassword()); cellPassword.setCellStyle(cellStyle); XSSFCell cellSex = row.createCell(3); cellSex.setCellValue(user.getUsex()); cellSex.setCellStyle(cellStyle); XSSFCell cellRole = row.createCell(4); cellRole.setCellValue(user.getRole()); cellRole.setCellStyle(cellStyle); XSSFCell cellLoveValue = row.createCell(5); cellLoveValue.setCellValue(user.getRole()); cellLoveValue.setCellStyle(cellStyle); XSSFCell cellPhone = row.createCell(6); cellPhone.setCellValue(user.getUphoto()); cellPhone.setCellStyle(cellStyle); XSSFCell cellAddress = row.createCell(7); cellAddress.setCellValue(user.getUaddress()); cellAddress.setCellStyle(cellStyle); } /** 表头 **/ public void titleExcel(XSSFRow row,XSSFCellStyle cellStyle){ XSSFCell cellId = row.createCell(0); cellId.setCellValue("用户ID"); cellId.setCellStyle(cellStyle); XSSFCell cellUserName = row.createCell(1); cellUserName.setCellValue("用户名"); cellUserName.setCellStyle(cellStyle); XSSFCell cellPassword = row.createCell(2); cellPassword.setCellValue("密码"); cellPassword.setCellStyle(cellStyle); XSSFCell cellSex = row.createCell(3); cellSex.setCellValue("性别"); cellSex.setCellStyle(cellStyle); XSSFCell cellRole = row.createCell(4); cellRole.setCellValue("角色"); cellRole.setCellStyle(cellStyle); XSSFCell cellLoveValue = row.createCell(5); cellLoveValue.setCellValue("爱心值"); cellLoveValue.setCellStyle(cellStyle); XSSFCell cellPhone = row.createCell(6); cellPhone.setCellValue("电话号码"); cellPhone.setCellStyle(cellStyle); XSSFCell cellAddress = row.createCell(7); cellAddress.setCellValue("地址"); cellAddress.setCellStyle(cellStyle); }
2. Hutool tool class encapsulation method export and import Excel
1.Introduce dependencies
Encapsulate poi into the tool class In the method
<!-- hutool --> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.7.20</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency>
2. Import demo
/** * Excel导入 */ @PostMapping("/import") public Result userImport(@RequestParam("file") MultipartFile file) throws Exception{ System.out.println(file.toString()); //InputStream inputStream = multipartFile.getInputStream(); InputStream inputStream = file.getInputStream(); ExcelReader reader = ExcelUtil.getReader(inputStream); //读取表的内容 List<List<Object>> list = reader.read(1); List<User> users = new ArrayList<>(); for(List<Object> row : list){ User user = new User(); user.setUname(row.get(0).toString()); user.setUpassword(row.get(1).toString()); user.setUsex(row.get(2).toString()); user.setRole(row.get(3).toString()); user.setUlove(Integer.valueOf(row.get(4).toString())); user.setUphoto(row.get(5).toString()); user.setUaddress(row.get(6).toString()); users.add(user); } //批量插入用户信息 mybatis-plus userService.saveBatch(users); return Result.success(); }
3. Export demo
/** * Excel导出 方法一 */ @GetMapping("/export") public Result userExport(HttpServletResponse response) throws Exception{ //查询全部的用户数据 List<User> list = userService.list(); //在内存里做操作,保存到浏览器 ExcelWriter writer = ExcelUtil.getWriter(true); //自定义标题别名 writer.addHeaderAlias("uname","用户名"); writer.addHeaderAlias("upassword","密码"); writer.addHeaderAlias("usex","性别"); writer.addHeaderAlias("role","角色"); writer.addHeaderAlias("ulove","爱心值"); writer.addHeaderAlias("uphoto","电话号码"); writer.addHeaderAlias("uaddress","地址"); //一次性写出list内的对象的Excel,使用默认样式,强制输出标题 writer.write(list,true); //设置浏览器响应格式 response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"); String filName= URLEncoder.encode("用户信息","UTF-8"); response.setHeader("Content-Disposition","attachment;filename="+filName+".xls"); ServletOutputStream outputStream=response.getOutputStream(); writer.flush(outputStream,true); outputStream.close(); writer.close(); return Result.success(); }
The above is the detailed content of How to use POI to import and export Excel tables in Java. For more information, please follow other related articles on the PHP Chinese website!

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version
God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor