java poi 操作 excel 读取本地Excel / 保存excel到本地 / url下载excel

pom.xml 配置poi版本

	
		org.apache.poi
		poi
		3.13
	
	
		org.apache.poi
		poi-ooxml
		3.13
			

读取本地Excel文件

	private HSSFWorkbook getWorkBookFromExcel(){
		POIFSFileSystem filein = new POIFSFileSystem(new FileInputStream("E:\\files\\11.xls")); 
		HSSFWorkbook workbook = new HSSFWorkbook(filein);
		HSSFSheet aging = workbook.getSheet("Aging");
		HSSFSheet tmp = workbook.getSheet("tmp");
		HSSFSheet sheet0 = workbook.getSheetAt(0);
		return workbook ;
	}

获取Sheet、行Row、单元格Cell

	private void setValue(HSSFWorkbook workbook ){
		HSSFSheet aging = workbook.getSheet("Aging");
		HSSFSheet tmp = workbook.getSheet("tmp");
		HSSFSheet sheet = workbook.getSheetAt(0);
		HSSFRow row= sheet .getRow(2);
		HSSFCell cell= row.getCell(12);
		HSSFCell cell2 =sheet.getRow(2).getCell(12);
		cell2.setValue("20181214");
	}

保存到本地

	private void SaveWorkbook(HSSFWorkbook workbook ){
		String newPath ="E:\\files\\20181214.xls";
		FileOutputStream fileOut = new FileOutputStream(newPath ); 
		workbook.write(fileOut); 
		fileOut.close(); 
	}

workbook转为excel后下载

参考博客 https://www.cnblogs.com/wangxiayun/p/9146486.html

public void getOutputStream(HttpServletResponse response) throws IOException {
	OutputStream output = response.getOutputStream();
	response.reset();
	response.setHeader("Content-disposition", "attachment; filename=test.xls");
	response.setContentType("application/msexcel");
	HSSFWorkbook workbook  =getWorkBookFromExcel(); 
	setValue(workbook );
	SaveWorkbook(workbook );
	workbook.write(output);
	if(output!=null) {
	    output.close();
	}
}

设置url下载(SpringMVC)

@RequestMapping("/excel/download")
public void download(HttpServletRequest request,HttpServletResponse response) throws IOException {
	getOutputStream(response);
}

后缀为.xls 和 .xlsx 操作

HSSFWorkbook:是操作Excel2003以前(包括2003)的版本,扩展名是.xls
XSSFWorkbook:是操作Excel2007的版本,扩展名是.xlsx
上面的例子我使用的是HSSFWorkbook
参考博客 https://www.cnblogs.com/liaojie970/p/7469350.html

你可能感兴趣的:(java,excel)