java 中Excel的匯入匯出
部分轉發原作者https://www.cnblogs.com/qdhxhz/p/8137282.html雨點的名字 的內容
java程式碼中的匯入匯出
首先在d盤建立一個xlsx檔案,然後再進行一系列操作
package com.aynu.excel; import java.io.FileOutputStream; import org.apache.poi.hssf.usermodel.HSSFWorkbook; /*我們在d盤下建立的是一個空白的xlsx檔案*/ public class ExcelSample1 { //建立一個Excel檔案 publicstatic void main(String[] args) throws Exception { //建立Excel文件物件 HSSFWorkbook wb = new HSSFWorkbook(); //建立Excel檔案 //將workbook.xlsx檔案轉換成一個輸出流物件 FileOutputStream fileout = new FileOutputStream("D:\\workbook.xlsx"); //將輸出流物件寫入到Excel文件物件中 wb.write(fileout);//為了避免佔用資源浪費記憶體將流物件關閉 fileout.close(); } }
first and foremost let's look at a few objects
HSSFWorkbook excel的文件物件
HSSFSheet excel的表單
HSSFRow excel的行
HSSFCell excel的格子單元
HSSFFont excel字型
HSSFDataFormat 日期格式
在poi1.7中才有以下2項:
HSSFHeader sheet頭
HSSFFooter sheet尾(只有列印的時候才能看到效果)
和這個樣式
HSSFCellStyle cell樣式
輔助操作包括
HSSFDateUtil 日期
HSSFPrintSetup 列印
HSSFErrorConstants 錯誤資訊表
package com.aynu.excel; import java.io.FileOutputStream; import java.util.Date; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFDataFormat; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; public class CreatCells { public static void main(String[] args) throws Exception { //建立一個Excel文件物件 HSSFWorkbook wb = new HSSFWorkbook(); //建立新的sheet物件 HSSFSheet sheet = wb.createSheet("new sheet"); //在sheet裡建立一行,引數為行號(第一行,此處可想象成陣列) HSSFRow row = sheet.createRow((short)0); //在row裡建立新cell(單元格),引數為列號(第一列) HSSFCell cell = row.createCell((short)0); //設定單元格型別的值 cell.setCellValue(1);//設定Cell整數型別的值 //Cell還可以設定各種型別的值但是要先建立這個單元格 row.createCell((short)1).setCellValue(1.2);//設定cell浮點型別的值 row.createCell((short)2).setCellValue(true);//設定cell布林型別的值 row.createCell((short)3).setCellValue("test"); //設定cell字元型別的值 //如果要建立單元格的樣式就要建立樣式的物件 HSSFCellStyle style = wb.createCellStyle(); //設定指定的日期格式 style.setDataFormat(HSSFDataFormat. getBuiltinFormat("m/d/yy h:mm")); HSSFCell dCell =row.createCell((short)4); dCell.setCellValue(new Date()); //設定cell為日期型別的值 dCell.setCellStyle(style); //設定該cell日期的顯示格式 HSSFCell csCell =row.createCell((short)5); csCell.setCellValue("中文測試_Chinese Words Test"); //設定中西文結合字串 row.createCell((short)6).setCellType(HSSFCell.CELL_TYPE_ERROR); //建立錯誤cell FileOutputStream fileOut = new FileOutputStream("workbook.xlsx"); wb.write(fileOut); fileOut.close(); } }
這個程式碼差生的效果是
在上邊的例子裡我們看到了要設定一個單元格里面資訊的格式(例如,要將資訊居中)設定的操作如下:
HSSFCellStyle cellstyle = wb.createCellStyle(); cellstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION); cell.setCellStyle(cellstyle); |
還有我們我們經常會用到的合併單元格,在這裡我們也有這樣的操作,程式碼如下:
sheet.addMergedRegion(new Region(1,(short)1,2,(short)4)); |
springmvc中的Excel的匯入匯出
springMVC生成excel檔案並匯出
從上面的寫法中我們就可以明白需要建立的物件
1、生成文件物件HSSHWorkbook。 2、通過HSSFWorkbook生成表單HSSFSheet。 3、通過HSSFSheet生成行HSSFRow 4、通過HSSFRow生成單元格HSSFCell。
步驟如下:
1.匯入jar包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
2.建立model物件
public class Person { private String id; private String name; private String password; private String age; public Person(String id, String name, String password, String age) { super(); this.id = id; this.name = name; this.password = password; this.age = age; } //提供set和get方法 }
3.建立頁面.jsp檔案
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <html> <!-- 正常資料匯出肯定要傳入引數,我這裡沒有用ajax傳參,簡單用連結傳參 --> <script type="text/javascript"> function download(){ var url="download_excel?id=10&name=張三"; window.open(url); } </script> <body> <form action=""> <input type="button" value="報表匯出" onclick="download()"/> </form> </body> </html>
4.建立控制器Controller
import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.ssm.service.impl.ExcleImpl; @Controller public class ExcleController { //這裡直接new了 ExcleImpl excleImpl=new ExcleImpl(); @RequestMapping(value="/jsp/download_excel") //獲取url連結上的引數 public @ResponseBody String dowm(HttpServletResponse response,@RequestParam("id") String id,@RequestParam("name") String name){ response.setContentType("application/binary;charset=UTF-8"); try{ ServletOutputStream out=response.getOutputStream(); try { //設定檔案頭:最後一個引數是設定下載檔名(這裡我們叫:張三.pdf) response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(name+".xls", "UTF-8")); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } String[] titles = { "使用者id", "使用者姓名", "使用者密碼", "使用者年齡" }; excleImpl.export(titles, out); return "success"; } catch(Exception e){ e.printStackTrace(); return "匯出資訊失敗"; } } }
第五步、ExcleImpl 報表匯出實現層
import java.util.ArrayList; import javax.servlet.ServletOutputStream; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import com.ssm.model.Person; public class ExcleImpl { public void export(String[] titles, ServletOutputStream out) throws Exception{ try{ // 第一步,建立一個workbook,對應一個Excel檔案 HSSFWorkbook workbook = new HSSFWorkbook(); // 第二步,在webbook中新增一個sheet,對應Excel檔案中的sheet HSSFSheet hssfSheet = workbook.createSheet("sheet1"); // 第三步,在sheet中新增表頭第0行,注意老版本poi對Excel的行數列數有限制short HSSFRow row = hssfSheet.createRow(0); // 第四步,建立單元格,並設定值表頭 設定表頭居中 HSSFCellStyle hssfCellStyle = workbook.createCellStyle(); //居中樣式 hssfCellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); HSSFCell hssfCell = null; for (int i = 0; i < titles.length; i++) { hssfCell = row.createCell(i);//列索引從0開始 hssfCell.setCellValue(titles[i]);//列名1 hssfCell.setCellStyle(hssfCellStyle);//列居中顯示 } // 第五步,寫入實體資料 Person person1=new Person("1","張三","123","26"); Person person2=new Person("2","李四","123","18"); Person person3=new Person("3","王五","123","77"); Person person4=new Person("4","徐小筱","123","1"); //這裡我把list當做資料庫啦 ArrayList<Person> list=new ArrayList<Person>(); list.add(person1); list.add(person2); list.add(person3); list.add(person4); for (int i = 0; i < list.size(); i++) { row = hssfSheet.createRow(i+1); Person person = list.get(i); // 第六步,建立單元格,並設定值 String id = null; if(person.getId() != null){ id = person.getId(); } row.createCell(0).setCellValue(id); String name = ""; if(person.getName() != null){ name = person.getName(); } row.createCell(1).setCellValue(name); String password = ""; if(person.getPassword() != null){ password = person.getPassword(); } row.createCell(2).setCellValue(password); String age=null; if(person.getAge() !=null){ age = person.getAge(); } row.createCell(3).setCellValue(age); } // 第七步,將檔案輸出到客戶端瀏覽器 try { workbook.write(out); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } }catch(Exception e){ e.printStackTrace(); throw new Exception("匯出資訊失敗!"); } } }
第六步:最終效果,當我點選報表匯出按鈕
springMVC匯入excel檔案資料到資料庫
第一步、匯入jar包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
第二步,建立Model物件
public class Family { //家庭編號 private String jtbh; //姓名 private String xm; //行業 private String hy; //備註 private String bz; /* * 提供set和get,toString方法 */ }
第三步.匯入excel介面 leadingexcel.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <html> <head> <script type="text/javascript" src="../js/jquery-1.7.1.js"></script> <script type="text/javascript" src="../js/jquery.form.js"></script> <script type="text/javascript"> /* ajax 方式上傳檔案操作 */ $(document).ready(function(){ $("#btn").click(function(){ if(checkData()){ $('#form1').ajaxSubmit({ url:'uploadExcel/ajax', dataType: 'text', success: resutlMsg, error: errorMsg }); function resutlMsg(msg){ alert(msg); $("#upfile").val(""); } function errorMsg(){ alert("匯入excel出錯!"); } } }); }); //JS校驗form表單資訊 function checkData(){ var fileDir = $("#upfile").val(); var suffix = fileDir.substr(fileDir.lastIndexOf(".")); if("" == fileDir){ alert("選擇需要匯入的Excel檔案!"); return false; } if(".xls" != suffix && ".xlsx" != suffix ){ alert("選擇Excel格式的檔案匯入!"); return false; } return true; } </script> </head> <body> <form method="POST" enctype="multipart/form-data" id="form1" action="uploadExcel/form"> <label>上傳檔案: </label> <input id="upfile" type="file" name="upfile"><br> <br> <input type="submit" value="表單提交" onclick="return checkData()"> <input type="button" value="ajax提交" id="btn" name="btn" > </form> </body> </html>
先講下,我這src引用路徑的時候發現,怎麼也引用不到,找了好久才發現,我在springmvc中沒有配置靜態檔案
springmvc.xml
<!-- 靜態資源訪問 -->
<mvc:default-servlet-handler/>
<!-- 當我僅配置上面的時候又發現src是引用到了,但是我的RequestMapping對映卻變成請求不到了,所以下面的也一定要加上 -->
<mvc:annotation-driven></mvc:annotation-driven>
第四步、LeadingExcelController.java
import java.io.InputStream; import java.io.PrintWriter; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import com.ssm.model.Family; import com.ssm.service.impl.ImportExcelUtil; @Controller @RequestMapping("/jsp/uploadExcel") public class LeadingExcelController { @RequestMapping("/form") public String form(HttpServletRequest request)throws Exception{ MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; InputStream in =null; List<List<Object>> listob = null; MultipartFile file = multipartRequest.getFile("upfile"); if(file.isEmpty()){ throw new Exception("檔案不存在!"); } in = file.getInputStream(); listob = new ImportExcelUtil().getBankListByExcel(in,file.getOriginalFilename()); in.close(); //該處可呼叫service相應方法進行資料儲存到資料庫中,現只對資料輸出 for (int i = 0; i < listob.size(); i++) { List<Object> lo = listob.get(i); Family family = new Family(); family.setJtbh(String.valueOf(lo.get(0))); family.setXm(String.valueOf(lo.get(1))); family.setHy(String.valueOf(lo.get(2))); family.setBz(String.valueOf(lo.get(3))); System.out.println("列印資訊-->"+family.toString()); } return null; } @RequestMapping(value="/ajax") public void ajaxUploadExcel(HttpServletRequest request,HttpServletResponse response) throws Exception { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; InputStream in =null; List<List<Object>> listob = null; MultipartFile file = multipartRequest.getFile("upfile"); if(file.isEmpty()){ throw new Exception("檔案不存在!"); } in = file.getInputStream(); listob = new ImportExcelUtil().getBankListByExcel(in,file.getOriginalFilename()); //該處可呼叫service相應方法進行資料儲存到資料庫中,現只對資料輸出 for (int i = 0; i < listob.size(); i++) { List<Object> lo = listob.get(i); Family family = new Family(); family.setJtbh(String.valueOf(lo.get(0))); family.setXm(String.valueOf(lo.get(1))); family.setHy(String.valueOf(lo.get(2))); family.setBz(String.valueOf(lo.get(3))); System.out.println("列印資訊-->"+family.toString()); } PrintWriter out = null; response.setCharacterEncoding("utf-8"); //防止ajax接受到的中文資訊亂碼 out = response.getWriter(); out.print("檔案匯入成功!"); out.flush(); out.close(); } }
第五步、ImportExcelUtil.java 報表匯入實現層
import java.io.IOException; import java.io.InputStream; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ImportExcelUtil { private final static String excel2003L =".xls"; //2003- 版本的excel private final static String excel2007U =".xlsx"; //2007+ 版本的excel /** * 描述:獲取IO流中的資料,組裝成List<List<Object>>物件 * @param in,fileName * @return * @throws IOException */ public List<List<Object>> getBankListByExcel(InputStream in,String fileName) throws Exception{ List<List<Object>> list = null; //建立Excel工作薄 Workbook work = this.getWorkbook(in,fileName); if(null == work){ throw new Exception("建立Excel工作薄為空!"); } Sheet sheet = null; Row row = null; Cell cell = null; list = new ArrayList<List<Object>>(); //遍歷Excel中所有的sheet for (int i = 0; i < work.getNumberOfSheets(); i++) { sheet = work.getSheetAt(i); if(sheet==null){continue;} //遍歷當前sheet中的所有行 for (int j = sheet.getFirstRowNum(); j < sheet.getLastRowNum(); j++) { row = sheet.getRow(j); if(row==null||row.getFirstCellNum()==j){continue;} //遍歷所有的列 List<Object> li = new ArrayList<Object>(); for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) { cell = row.getCell(y); li.add(this.getCellValue(cell)); } list.add(li); } } in.close(); return list; } /** * 描述:根據檔案字尾,自適應上傳檔案的版本 * @param inStr,fileName * @return * @throws Exception */ public Workbook getWorkbook(InputStream inStr,String fileName) throws Exception{ Workbook wb = null; String fileType = fileName.substring(fileName.lastIndexOf(".")); if(excel2003L.equals(fileType)){ wb = new HSSFWorkbook(inStr); //2003- }else if(excel2007U.equals(fileType)){ wb = new XSSFWorkbook(inStr); //2007+ }else{ throw new Exception("解析的檔案格式有誤!"); } return wb; } /** * 描述:對錶格中數值進行格式化 * @param cell * @return */ public Object getCellValue(Cell cell){ Object value = null; DecimalFormat df = new DecimalFormat("0"); //格式化number String字元 SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd"); //日期格式化 DecimalFormat df2 = new DecimalFormat("0.00"); //格式化數字 switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: value = cell.getRichStringCellValue().getString(); break; case Cell.CELL_TYPE_NUMERIC: if("General".equals(cell.getCellStyle().getDataFormatString())){ value = df.format(cell.getNumericCellValue()); }else if("m/d/yy".equals(cell.getCellStyle().getDataFormatString())){ value = sdf.format(cell.getDateCellValue()); }else{ value = df2.format(cell.getNumericCellValue()); } break; case Cell.CELL_TYPE_BOOLEAN: value = cell.getBooleanCellValue(); break; case Cell.CELL_TYPE_BLANK: value = ""; break; default: break; } return value; } }
第六步:最終效果,當我點選通過表單和ajax提交時
(1)先展示上傳的xls檔案內容
(2)最終控制檯打出:
(3)通過ajax匯入成功,前端也會提示