溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

Java?WorkBook對(duì)Excel的基本操作方法有哪些

發(fā)布時(shí)間:2023-03-31 15:22:40 來(lái)源:億速云 閱讀:193 作者:iii 欄目:開(kāi)發(fā)技術(shù)

這篇文章主要介紹了Java WorkBook對(duì)Excel的基本操作方法有哪些的相關(guān)知識(shí),內(nèi)容詳細(xì)易懂,操作簡(jiǎn)單快捷,具有一定借鑒價(jià)值,相信大家閱讀完這篇Java WorkBook對(duì)Excel的基本操作方法有哪些文章都會(huì)有所收獲,下面我們一起來(lái)看看吧。

1、異常java.lang.NoClassDefFoundError: org/apache/poi/UnsupportedFileFormatException

  解決方法:使用的poi的相關(guān)jar包一定版本一定要相同?。。。。?/strong>

2、maven所使用jar包,沒(méi)有使用maven的話(huà),就用poi-3.9.jar和poi-ooxml-3.9.jar(這個(gè)主要是用于Excel2007以后的版本)兩個(gè)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對(duì)象(excel的文檔對(duì)象)
	HSSFWorkbook wb = new HSSFWorkbook();
	//建立新的sheet對(duì)象(excel的表單)
	HSSFSheet sheet=wb.createSheet("成績(jī)表");
	//在sheet里創(chuàng)建第一行,參數(shù)為行索引(excel的行),可以是0~65535之間的任何一個(gè)
	HSSFRow row1=sheet.createRow(0);
	//創(chuàng)建單元格(excel的單元格,參數(shù)為列索引,可以是0~255之間的任何一個(gè)
	HSSFCell cell=row1.createCell(0);
	//設(shè)置單元格內(nèi)容
	cell.setCellValue("學(xué)員考試成績(jī)一覽表");
	//合并單元格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("班級(jí)");
	row2.createCell(2).setCellValue("筆試成績(jī)");
	row2.createCell(3).setCellValue("機(jī)試成績(jī)");
	//在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;
}

補(bǔ)充說(shuō)明亂碼問(wèn)題

  1、文件名亂碼(我發(fā)現(xiàn)只要解決了文件名亂碼,其他亂碼也會(huì)跟著解決)response.setHeader("Content-disposition", "attachment; filename=中文.xls");

  這個(gè)方法可以當(dāng)做一個(gè)公用方法來(lái)使用,以后有亂碼的都可以調(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)用的時(shí)候,response.setHeader("Content-disposition", "attachment; filename="+toUtf8String("中文.xls"));

 我上網(wǎng)查的時(shí)候,網(wǎng)上是說(shuō)

 今天要說(shuō)的是在創(chuàng)建工作表時(shí),用中文做文件名和工作表名會(huì)出現(xiàn)亂碼的問(wèn)題,先說(shuō)以中文作為工作表名,大家創(chuàng)建工作表的代碼一般如下:

    HSSFWorkbook workbook = new HSSFWorkbook();//創(chuàng)建EXCEL文件

        HSSFSheet  sheet= workbook.createSheet(sheetName);    //創(chuàng)建工作表

    這樣在用英文名作為工作表名是沒(méi)問(wèn)題的,但如果sheetName是中文字符,就會(huì)出現(xiàn)亂碼,解決的方法如下代碼:

    HSSFSheet  sheet= workbook.createSheet();

    workbook.setSheetName(0, sheetName,(short)1); //這里(short)1是解決中文亂碼的關(guān)鍵;而第一個(gè)參數(shù)是工作表的索引號(hào)。       

但是我發(fā)現(xiàn)根本沒(méi)有這個(gè)方法,只需要改了文件名的亂碼,其他亂碼自然就解決了?。。?/p>

關(guān)于“Java WorkBook對(duì)Excel的基本操作方法有哪些”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對(duì)“Java WorkBook對(duì)Excel的基本操作方法有哪些”知識(shí)都有一定的了解,大家如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI