excel使用poi操作。
阿新 • • 發佈:2019-01-03
- String real_path = request.getSession().getServletContext().getRealPath("/");//獲取檔案路徑,我是通過模板進行匯出,在專案中拿到模板
- if (!real_path.endsWith("/")) {
- real_path = real_path + "/";
- }
- String r_url = real_path + "excel/bixuan.xls";//拼接好檔案的完整路徑
- String excelPath = r_url;
- String sheetName = "Sheet1";//獲取到不同的sheet頁。
- String sheetName1 = "Sheet2";
//拿到檔案路徑後建立excel物件
- File f = new File(excelPath );
- FileInputStream fis =fis = new FileInputStream(f);
- HSSFWorkbook wb =wb = new HSSFWorkbook(fis);
- HSSFWorkbook wb = util.createWorkBook(excelPath);
- HSSFSheet sheet = wb.getSheet(sheetName)
- HSSFSheet sheet1 = wb.getSheet(sheetName1)
//設定樣式
- HSSFCellStyle style = wb.createCellStyle();
- style.setWrapText(true);
- style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
- style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
//設定邊框
- style.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下邊框
- style.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左邊框
- style.setBorderTop(HSSFCellStyle.BORDER_THIN);//上邊框
- style.setBorderRight(HSSFCellStyle.BORDER_THIN);//右邊框
//設定字型
- HSSFFont font2 = wb.createFont();
- font2.setFontName("仿宋_GB2312");
- font2.setFontHeightInPoints((short) 9);//字型大小
- style.setFont(font2);
- sheet.protectSheet("123456");//設定密碼,保護單元格
- sheet1.protectSheet("123456");
- style.setWrapText(true);//一定要有這個,否則設定單元格密碼失效
//在excel中插入的行
- sheet.shiftRows(len-1, len+20, find.size()-5, true, false);//引數詳解 1從這行行開始移動,2到那行結束 3移動的數量
//合併單元格後,邊框樣式對合並的單元格不起作用,需要用下面程式碼處理
- CellRangeAddress cellRangeAddress = new CellRangeAddress(len-1,len-1,3,5);//引數,合併單元格的開始行數,與結束行數。
- int addMergedRegion = sheet.addMergedRegion(cellRangeAddress);//合併單元格
- sheet.getRow(len-1).getCell(2).setCellStyle(style);設定樣式
//不同瀏覽器對匯出的excel有不同的編碼,做如下處理
- if(isMSBrowser(request)){
- xlsName = java.net.URLEncoder.encode(xlsName, "utf-8") + ".xls";
- } else {
- xlsName = new String(xlsName.getBytes("utf-8"), "iso-8859-1") + ".xls";
- }
//判斷是不是ie瀏覽器
- public boolean isMSBrowser(HttpServletRequest request) {
- String[] IEBrowserSignals = {"MSIE", "Trident", "Edge"};
- String userAgent = request.getHeader("User-Agent");
- for (String signal : IEBrowserSignals) {
- if (userAgent.contains(signal)){
- return true;
- }
- }
- return false;
- }
//封裝一下對合並單元格的邊框處理
- public void setBorderStyle(int border, CellRangeAddress region, HSSFSheet sheet, HSSFWorkbook wb){
- RegionUtil.setBorderBottom(border, region, sheet, wb);//下邊框
- RegionUtil.setBorderLeft(border, region, sheet, wb);//左邊框
- RegionUtil.setBorderRight(border, region, sheet, wb); //右邊框
- RegionUtil.setBorderTop(border, region, sheet, wb); //上邊框
- }
借鑑部落格:https://www.cnblogs.com/staticxy/p/6122336.html
https://www.cnblogs.com/dcncy/p/8041657.html