Java?WorkBook對Excel的基本操作方法
1、異常java.lang.NoClassDefFoundError: org/apache/poi/UnsupportedFileFormatException
解決方法:使用的poi的相關(guān)jar包一定版本一定要相同?。。。?!
2、maven所使用jar包,沒有使用maven的話,就用poi-3.9.jar和poi-ooxml-3.9.jar(這個主要是用于Excel2007以后的版本)兩個jar包就行()
<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、java導(dǎo)入Excel
先上傳Excel
//上傳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; }
在讀取Excel里面的內(nèi)容
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>(); // 循環(huán)工作表Sheet for (int numSheet = 0; numSheet <hssfWorkbook.getNumberOfSheets(); numSheet++) { //HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet); Sheet hssfSheet = hssfWorkbook.getSheetAt(numSheet); if (hssfSheet == null) { continue; } // 循環(huán)行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、導(dǎo)出Excel
//創(chuàng)建Excel @RequestMapping("/createExcel") public String createExcel(HttpServletResponse response) throws IOException { //創(chuàng)建HSSFWorkbook對象(excel的文檔對象) HSSFWorkbook wb = new HSSFWorkbook(); //建立新的sheet對象(excel的表單) HSSFSheet sheet=wb.createSheet("成績表"); //在sheet里創(chuàng)建第一行,參數(shù)為行索引(excel的行),可以是0~65535之間的任何一個 HSSFRow row1=sheet.createRow(0); //創(chuàng)建單元格(excel的單元格,參數(shù)為列索引,可以是0~255之間的任何一個 HSSFCell cell=row1.createCell(0); //設(shè)置單元格內(nèi)容 cell.setCellValue("學(xué)員考試成績一覽表"); //合并單元格CellRangeAddress構(gòu)造參數(shù)依次表示起始行,截至行,起始列, 截至列 sheet.addMergedRegion(new CellRangeAddress(0,0,0,3)); //在sheet里創(chuàng)建第二行 HSSFRow row2=sheet.createRow(1); //創(chuàng)建單元格并設(shè)置單元格內(nèi)容 row2.createCell(0).setCellValue("姓名"); row2.createCell(1).setCellValue("班級"); row2.createCell(2).setCellValue("筆試成績"); row2.createCell(3).setCellValue("機試成績"); //在sheet里創(chuàng)建第三行 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; }
補充說明亂碼問題
1、文件名亂碼(我發(fā)現(xiàn)只要解決了文件名亂碼,其他亂碼也會跟著解決)response.setHeader("Content-disposition", "attachment; filename=中文.xls");
這個方法可以當(dāng)做一個公用方法來使用,以后有亂碼的都可以調(diào)用此方法
public static String toUtf8String(String s){ StringBuffer sb = new StringBuffer(); for (int i=0;i<s.length();i++){ char c = s.charAt(i); if (c >= 0 && c <= 255){sb.append(c);} else{ byte[] b; try { b = Character.toString(c).getBytes("utf-8");} catch (Exception ex) { System.out.println(ex); b = new byte[0]; } for (int j = 0; j < b.length; j++) { int k = b[j]; if (k < 0) k += 256; sb.append("%" + Integer.toHexString(k).toUpperCase()); } } } return sb.toString(); }
調(diào)用的時候,response.setHeader("Content-disposition", "attachment; filename="+toUtf8String("中文.xls"));
我上網(wǎng)查的時候,網(wǎng)上是說
今天要說的是在創(chuàng)建工作表時,用中文做文件名和工作表名會出現(xiàn)亂碼的問題,先說以中文作為工作表名,大家創(chuàng)建工作表的代碼一般如下:
HSSFWorkbook workbook = new HSSFWorkbook();//創(chuàng)建EXCEL文件
HSSFSheet sheet= workbook.createSheet(sheetName); //創(chuàng)建工作表
這樣在用英文名作為工作表名是沒問題的,但如果sheetName是中文字符,就會出現(xiàn)亂碼,解決的方法如下代碼:
HSSFSheet sheet= workbook.createSheet();
workbook.setSheetName(0, sheetName,(short)1); //這里(short)1是解決中文亂碼的關(guān)鍵;而第一個參數(shù)是工作表的索引號。
但是我發(fā)現(xiàn)根本沒有這個方法,只需要改了文件名的亂碼,其他亂碼自然就解決了?。?!
到此這篇關(guān)于Java WorkBook對Excel的基本操作的文章就介紹到這了,更多相關(guān)Java WorkBook Excel操作內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java 創(chuàng)建并應(yīng)用PPT幻燈片母版的方法示例
幻燈片母版可供用戶設(shè)置幻燈片的樣式,本文將介紹如何用Java創(chuàng)建并應(yīng)用單個或多個幻燈片母版。感興趣可以了解一下2020-06-06Java中繼承thread類與實現(xiàn)Runnable接口的比較
這篇文章主要介紹了Java中繼承thread類與實現(xiàn)Runnable接口的比較的相關(guān)資料,需要的朋友可以參考下2017-06-06一文搞懂SpringBoot如何利用@Async實現(xiàn)異步調(diào)用
異步調(diào)用幾乎是處理高并發(fā),解決性能問題常用的手段,如何開啟異步調(diào)用?SpringBoot中提供了非常簡單的方式,就是一個注解@Async。今天我們重新認(rèn)識一下@Async,以及注意事項2022-09-09