What are the basic operating methods of Java WorkBook on Excel?
1. Exception java.lang.NoClassDefFoundError: org/apache/poi/UnsupportedFileFormatException
Solution: The versions of the related jar packages used for poi must be the same! ! ! ! !
2. The jar package used by maven. If maven is not used, use poi-3.9.jar and poi-ooxml-3.9.jar (this is mainly used for Excel2007 and later versions). jar package will do ()
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.9</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.9</version> </dependency>
3. Import Excel from java
Upload Excel first
//上传Excel @RequestMapping("/uploadExcel") public boolean uploadExcel(@RequestParam MultipartFile file,HttpServletRequest request) throws IOException { if(!file.isEmpty()){ String filePath = file.getOriginalFilename(); //windows String savePath = request.getSession().getServletContext().getRealPath(filePath); //linux //String savePath = "/home/odcuser/webapps/file"; File targetFile = new File(savePath); if(!targetFile.exists()){ targetFile.mkdirs(); } file.transferTo(targetFile); return true; } return false; }
Read the content in Excel
public static void readExcel() throws Exception{ InputStream is = new FileInputStream(new File(fileName)); Workbook hssfWorkbook = null; if (fileName.endsWith("xlsx")){ hssfWorkbook = new XSSFWorkbook(is);//Excel 2007 }else if (fileName.endsWith("xls")){ hssfWorkbook = new HSSFWorkbook(is);//Excel 2003 } // HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is); // XSSFWorkbook hssfWorkbook = new XSSFWorkbook(is); User student = null; List<User> list = new ArrayList<User>(); // 循环工作表Sheet for (int numSheet = 0; numSheet <hssfWorkbook.getNumberOfSheets(); numSheet++) { //HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet); Sheet hssfSheet = hssfWorkbook.getSheetAt(numSheet); if (hssfSheet == null) { continue; } // 循环行Row for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) { //HSSFRow hssfRow = hssfSheet.getRow(rowNum); Row hssfRow = hssfSheet.getRow(rowNum); if (hssfRow != null) { student = new User(); //HSSFCell name = hssfRow.getCell(0); //HSSFCell pwd = hssfRow.getCell(1); Cell name = hssfRow.getCell(0); Cell pwd = hssfRow.getCell(1); //这里是自己的逻辑 student.setUserName(name.toString()); student.setPassword(pwd.toString()); list.add(student); } } } }
4. Export Excel
//创建Excel @RequestMapping("/createExcel") public String createExcel(HttpServletResponse response) throws IOException { //创建HSSFWorkbook对象(excel的文档对象) HSSFWorkbook wb = new HSSFWorkbook(); //建立新的sheet对象(excel的表单) HSSFSheet sheet=wb.createSheet("成绩表"); //在sheet里创建第一行,参数为行索引(excel的行),可以是0~65535之间的任何一个 HSSFRow row1=sheet.createRow(0); //创建单元格(excel的单元格,参数为列索引,可以是0~255之间的任何一个 HSSFCell cell=row1.createCell(0); //设置单元格内容 cell.setCellValue("学员考试成绩一览表"); //合并单元格CellRangeAddress构造参数依次表示起始行,截至行,起始列, 截至列 sheet.addMergedRegion(new CellRangeAddress(0,0,0,3)); //在sheet里创建第二行 HSSFRow row2=sheet.createRow(1); //创建单元格并设置单元格内容 row2.createCell(0).setCellValue("姓名"); row2.createCell(1).setCellValue("班级"); row2.createCell(2).setCellValue("笔试成绩"); row2.createCell(3).setCellValue("机试成绩"); //在sheet里创建第三行 HSSFRow row3=sheet.createRow(2); row3.createCell(0).setCellValue("李明"); row3.createCell(1).setCellValue("As178"); row3.createCell(2).setCellValue(87); row3.createCell(3).setCellValue(78); //.....省略部分代码 //输出Excel文件 OutputStream output=response.getOutputStream(); response.reset(); response.setHeader("Content-disposition", "attachment; filename=details.xls"); response.setContentType("application/msexcel"); wb.write(output); output.close(); return null; }
Supplementary explanation of garbled code problem
1. Garbled file name (I found that as long as the garbled file name is solved, other garbled characters will also be solved) response.setHeader("Content-disposition", "attachment; filename = Chinese. ("Content-disposition", "attachment; filename=" toUtf8String("Chinese.xls"));
When I checked on the Internet, it said
What I want to talk about today is When creating a worksheet, using Chinese as the file name and worksheet name will cause garbled characters. First, let’s use Chinese as the worksheet name. The code for creating a worksheet is generally as follows:
HSSFWorkbook workbook = new HSSFWorkbook() ;//Create EXCEL file
HSSFSheet sheet= workbook.createSheet(sheetName); //Create worksheet
This way, it is okay to use the English name as the worksheet name, but if sheetName If it is Chinese characters, garbled characters will appear. The solution is as follows:
HSSFSheet sheet= workbook.createSheet();
workbook.setSheetName(0, sheetName,(short)1); //Here (short) 1 is the key to solving Chinese garbled characters; and the first parameter is the index number of the worksheet.
But I found that there is no such method at all. I only need to change the garbled characters in the file name, and other garbled characters will be solved naturally! ! !
The above is the detailed content of What are the basic operating methods of Java WorkBook on Excel?. For more information, please follow other related articles on the PHP Chinese website!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics











Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.
