背景:1.pringmvc 框架下 的excel 導入導出
2.OI 操作office.
頁面代碼:
<div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg" style="width:400px;"> <div class="modal-content"> <div style="height:300px;padding:10px;"> <h1>批量導入商品信息</h1> <div style="margin-top:20px;padding:0px 5px 15px 5px;"> <span><strong>1.下載模板 > 2.導入模板 >3.導入完成</strong></span><br/> <span><strong>溫馨提示:</strong></span> <div style="line-height:50px;">導入模板格式不能修改,否則會導致導入失敗!</div> <a href="${webRoot}/product/downExcel">下載導入模板</a> </div> <div> <form action="${webRoot}/product/importExcel" id="excelForm" method="post" enctype="multipart/form-data"> <input type="file" name="file" /> <div style="text-align:right;padding-right:50px;"> <button type="button" id="import" class="btn btn-default" >導入</button> <script> $("#import").click(function(){ $("#excelForm").submit(); }); </script> </div> </form> </div> </div> </div> </div> </div>
Controller 代碼:
@RequestMapping("importExcel")
public String addComm(ModelMap model, HttpServletRequest request) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multipartRequest.getFile("file");
String[][] result = null;
ExportUtil exportUtil = new ExportUtil();
try {
exportUtil.SaveFileFromInputStream(file.getInputStream(),
request.getSession().getServletContext()
.getRealPath(File.separator)+"upload", "product.xls");
File file1 = new File(request.getSession().getServletContext()
.getRealPath(File.separator)+"upload" + "/product.xls");
result =exportUtil.getData(file1, 4);
} catch (Exception ex) {
System.out.println("上傳文件失敗");
ex.printStackTrace();
}
if (result == null)
return null;
User user = (User)request.getSession().getAttribute("user");
if(user==null) return "";
int rowLength = result.length;
List<Product> proList =exportUtil.doProduct(rowLength, result,user);
ps.excelAdd(proList);
return "redirect:/product/getproduct";
}
@RequestMapping("downExcel")
@ResponseBody
public String downExcel(HttpServletResponse response){
try {
ServletOutputStream outputStream = response.getOutputStream();
String fileName = new String(("商品導入模板").getBytes(), "ISO8859_1");
response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");// 組裝附件名稱和格式
es.exportExcel(outputStream,false);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
@RequestMapping("exportExcel")
@ResponseBody
public String exportExcel(HttpServletResponse response){
try {
ServletOutputStream outputStream = response.getOutputStream();
String fileName = new String(("藍圖進銷存商品導出").getBytes(), "ISO8859_1");
response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");// 組裝附件名稱和格式
es.exportExcel(outputStream,true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
ExportService:
package com.ly.jxc.service; import java.io.IOException; import java.util.List; import javax.annotation.Resource; 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 org.apache.poi.ss.util.CellRangeAddress; import org.springframework.stereotype.Service; import com.ly.jxc.dao.ProductClassDAO; import com.ly.jxc.dao.ProductDAO; import com.ly.jxc.dao.ProductUnitDAO; import com.ly.jxc.entity.Product; import com.ly.jxc.entity.ProductClass; import com.ly.jxc.entity.ProductUnit; import com.ly.jxc.util.ExportUtil; @Service public class ExportService { @Resource private ProductUnitDAO pud; @Resource private ProductClassDAO pcd; @Resource private ProductDAO pd; public void exportExcel(ServletOutputStream outputStream,boolean isDwon) { List<ProductUnit> puList = pud.getAllUnit(); List<ProductClass> pcList = pcd.GetAllProductClass(); // 創建一個workbook 對應一個excel應用文件 // HSSWorkbook 是03版excel 的個格式,XSSWorkbook 是07以上版本,HSS 和 XSS 開頭分別代表03,07可以切換 HSSFWorkbook workBook = new HSSFWorkbook(); // 在workbook中添加一個sheet,對應Excel文件中的sheet HSSFSheet sheet = workBook.createSheet("商品導入導出"); //表格默認行寬度 sheet.setDefaultColumnWidth(15); sheet.setDefaultRowHeightInPoints(100); ExportUtil exportUtil = new ExportUtil(workBook, sheet); //設置單元格格式 HSSFCellStyle headStyle = exportUtil.getHeadStyle(false); HSSFCellStyle bodyStyle = exportUtil.getBodyStyle(); //創建單元格 HSSFCell cell = null; //合並單元格 sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 8)); //創建一行 HSSFRow descRow = sheet.createRow(0); //設置行高 單位是像素 descRow.setHeightInPoints(80); //表示穿件的單元格是在第一行 cell=descRow.createCell(0); //設置單元格格式 cell.setCellStyle(exportUtil.getHeadStyle(true)); //設置單元格值 cell.setCellValue("商品單位和類型填寫必須填寫對應的數字ID,否則會導入失敗!"); // 構建表頭 HSSFRow unitRow = sheet.createRow(1); unitRow.setHeightInPoints(40); cell=unitRow.createCell(0); cell.setCellStyle(headStyle); cell.setCellValue("商品單位-ID:"); // 構建商品單位數據,動態構建導出數據 if (puList != null && puList.size() > 0) { for (int j = 0; j < puList.size(); j++) { ProductUnit pu = puList.get(j); cell=unitRow.createCell(j+1); cell.setCellStyle(bodyStyle); cell.setCellValue(pu.getName()+"--"+pu.getpId()); } } // 構建商品類型表頭 ,動態構建導出數據 HSSFRow classRow = sheet.createRow(2); classRow.setHeightInPoints(40); cell=classRow.createCell(0); cell.setCellStyle(headStyle); cell.setCellValue("商品類型-ID:"); // 構建商品類型數據 if (pcList != null && pcList.size() > 0) { for (int j = 0; j < pcList.size(); j++) { ProductClass pc = pcList.get(j); cell=classRow.createCell(j+1); cell.setCellStyle(bodyStyle); cell.setCellValue(pc.getName()+"--"+pc.getProductClass_ID()); } } HSSFRow bodyRow = sheet.createRow(3); bodyRow.setHeightInPoints(40); cell = bodyRow.createCell(0); cell.setCellStyle(headStyle); cell.setCellValue("條碼"); cell = bodyRow.createCell(1); cell.setCellStyle(headStyle); cell.setCellValue("名字"); cell = bodyRow.createCell(2); cell.setCellStyle(headStyle); cell.setCellValue("類別ID"); cell = bodyRow.createCell(3); cell.setCellStyle(headStyle); cell.setCellValue("產品規格"); cell = bodyRow.createCell(4); cell.setCellStyle(headStyle); cell.setCellValue("產品單位"); cell = bodyRow.createCell(5); cell.setCellStyle(headStyle); cell.setCellValue("出售價格"); cell = bodyRow.createCell(6); cell.setCellStyle(headStyle); cell.setCellValue("進貨價格"); cell = bodyRow.createCell(7); cell.setCellStyle(headStyle); cell.setCellValue("最低價格"); cell = bodyRow.createCell(8); cell.setCellStyle(headStyle); cell.setCellValue("備注"); //如果是導出商品,則需要將商品數據寫入 if(isDwon){ List<Product> proList = pd.getAllProducts(); for (int i = 0; i < proList.size(); i++) { Product p =proList.get(i); HSSFRow dateRow = sheet.createRow(4+i); bodyRow.setHeightInPoints(40); cell = dateRow.createCell(0); cell.setCellStyle(bodyStyle); cell.setCellValue(p.getpId()); cell = dateRow.createCell(1); cell.setCellStyle(bodyStyle); cell.setCellValue(p.getName()); cell = dateRow.createCell(2); cell.setCellStyle(bodyStyle); cell.setCellValue(p.getpList()); cell = dateRow.createCell(3); cell.setCellStyle(bodyStyle); cell.setCellValue(p.getPsID()); cell = dateRow.createCell(4); cell.setCellStyle(bodyStyle); cell.setCellValue(p.getpUtilId()); cell = dateRow.createCell(5); cell.setCellStyle(bodyStyle); cell.setCellValue(p.getPrice()); cell = dateRow.createCell(6); cell.setCellStyle(bodyStyle); cell.setCellValue(p.getStockPrice()); cell = dateRow.createCell(7); cell.setCellStyle(bodyStyle); cell.setCellValue(p.getLowestPrice()); cell = dateRow.createCell(8); cell.setCellStyle(bodyStyle); cell.setCellValue(p.getRemark()); } } try { workBook.write(outputStream); outputStream.flush(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } finally { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }
輔助類ExportUtil:
package com.ly.jxc.util; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import javax.servlet.http.HttpSession; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFDateUtil; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFFont; import org.springframework.beans.factory.annotation.Autowired; import com.ly.jxc.entity.Product; import com.ly.jxc.entity.User; public class ExportUtil { private HSSFWorkbook wb = null; private HSSFSheet sheet = null; @Autowired HttpSession session; /** * @param wb * @param sheet */ public ExportUtil(HSSFWorkbook wb, HSSFSheet sheet) { this.wb = wb; this.sheet = sheet; } public ExportUtil() { } /** * 合並單元格后給合並后的單元格加邊框 * * @param region * @param cs */ public void setRegionStyle(CellRangeAddress region, XSSFCellStyle cs) { int toprowNum = region.getFirstRow(); for (int i = toprowNum; i <= region.getLastRow(); i++) { HSSFRow row = sheet.getRow(i); for (int j = region.getFirstColumn(); j <= region.getLastColumn(); j++) { HSSFCell cell = row.getCell(j);// XSSFCellUtil.getCell(row, // (short) j); cell.setCellStyle(cs); } } } /** * 設置表頭的單元格樣式 * * @return */ public HSSFCellStyle getHeadStyle(boolean isalert) { // 創建單元格樣式 HSSFCellStyle cellStyle = wb.createCellStyle(); // 設置單元格的背景顏色為淡藍色 if (!isalert) cellStyle.setFillForegroundColor(HSSFColor.PALE_BLUE.index); else cellStyle.setFillForegroundColor(HSSFColor.RED.index); cellStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND); // 設置單元格居中對齊 cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 設置單元格垂直居中對齊 cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); // 創建單元格內容顯示不下時自動換行 cellStyle.setWrapText(true); // 設置單元格字體樣式 HSSFFont font = wb.createFont(); // 設置字體加粗 font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD); font.setFontName("宋體"); if (isalert) { font.setColor(HSSFColor.WHITE.index); } font.setFontHeight((short) 200); cellStyle.setFont(font); // 設置單元格邊框為細線條 cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN); cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN); cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN); cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN); return cellStyle; } /** * 設置表體的單元格樣式 * * @return */ public HSSFCellStyle getBodyStyle() { // 創建單元格樣式 HSSFCellStyle cellStyle = wb.createCellStyle(); // 設置單元格居中對齊 cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 設置單元格垂直居中對齊 cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); // 創建單元格內容顯示不下時自動換行 cellStyle.setWrapText(true); // 設置單元格字體樣式 HSSFFont font = wb.createFont(); // 設置字體加粗 font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD); font.setFontName("宋體"); font.setFontHeight((short) 200); cellStyle.setFont(font); // 設置單元格邊框為細線條 cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN); cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN); cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN); cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN); return cellStyle; } // 將MultipartFile 轉換為File public static void SaveFileFromInputStream(InputStream stream, String path, String savefile) throws IOException { FileOutputStream fs = new FileOutputStream(path + "/" + savefile); // System.out.println("------------"+path + "/"+ savefile); byte[] buffer = new byte[1024 * 1024]; int bytesum = 0; int byteread = 0; while ((byteread = stream.read(buffer)) != -1) { bytesum += byteread; fs.write(buffer, 0, byteread); fs.flush(); } fs.close(); stream.close(); } /** * * 讀取Excel的內容,第一維數組存儲的是一行中格列的值,二維數組存儲的是多少個行 * * @param file * 讀取數據的源Excel * * @param ignoreRows * 讀取數據忽略的行數,比喻行頭不需要讀入 忽略的行數為1 * * @return 讀出的Excel中數據的內容 * * @throws FileNotFoundException * * @throws IOException */ public static String[][] getData(File file, int ignoreRows)throws Exception { List<String[]> result = new ArrayList<String[]>(); int rowSize = 0; BufferedInputStream in = new BufferedInputStream(new FileInputStream(file)); // 打開HSSFWorkbook POIFSFileSystem fs = new POIFSFileSystem(in); HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFCell cell = null; for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) { HSSFSheet st = wb.getSheetAt(sheetIndex); // 第一行為標題,不取 for (int rowIndex = ignoreRows; rowIndex <= st.getLastRowNum(); rowIndex++) { HSSFRow row = st.getRow(rowIndex); if (row == null) { continue; } int tempRowSize = row.getLastCellNum() + 1; if (tempRowSize > rowSize) { rowSize = tempRowSize; } String[] values = new String[rowSize]; Arrays.fill(values, ""); boolean hasValue = false; for (short columnIndex = 0; columnIndex <= row.getLastCellNum(); columnIndex++) { String value = ""; cell = row.getCell(columnIndex); if (cell != null) { // 注意:一定要設成這個,否則可能會出現亂碼 switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_STRING: value = cell.getStringCellValue(); break; case HSSFCell.CELL_TYPE_NUMERIC: if (HSSFDateUtil.isCellDateFormatted(cell)) { Date date = cell.getDateCellValue(); if (date != null) { value = new SimpleDateFormat("yyyy-MM-dd").format(date); } else { value = ""; } } else { value = new DecimalFormat("0").format(cell.getNumericCellValue()); } break; case HSSFCell.CELL_TYPE_FORMULA: // 導入時如果為公式生成的數據則無值 if (!cell.getStringCellValue().equals("")) { value = cell.getStringCellValue(); } else { value = cell.getNumericCellValue() + ""; } break; case HSSFCell.CELL_TYPE_BLANK: break; case HSSFCell.CELL_TYPE_ERROR: value = ""; break; case HSSFCell.CELL_TYPE_BOOLEAN: value = (cell.getBooleanCellValue() == true ? "Y" : "N"); break; default: value = ""; } } if (columnIndex == 0 && value.trim().equals("")) { break; } values[columnIndex] = rightTrim(value); hasValue = true; } if (hasValue) { result.add(values); } } } in.close(); String[][] returnArray = new String[result.size()][rowSize]; for (int i = 0; i < returnArray.length; i++) { returnArray[i] = (String[]) result.get(i); } return returnArray; } /** * * 去掉字符串右邊的空格 * * @param str * 要處理的字符串 * * @return 處理后的字符串 */ public static String rightTrim(String str) { if (str == null) { return ""; } int length = str.length(); for (int i = length - 1; i >= 0; i--) { if (str.charAt(i) != 0x20) { break; } length--; } return str.substring(0, length); } public List<Product> doProduct(int rowLength,String[][] result,User user){ // 默認從1 開始 本來是為0 剔除掉 List<Product> proList = new ArrayList<Product>(); Date date = new Date(); for (int i = 0; i < rowLength; i++) { Product pro = new Product(); for (int j = 0; j < result[i].length; j++) {// 默認從1開始添加 // 客戶ID 客戶名 客戶類型 客戶電話 客戶狀態 創建時間 放出時間 跟入時間 跟入人 放出人 // 27 法規和熱 特級 1212121 1 41773 2014-05-14 10:20:48.0 yq1012 // 整理 id 去掉 。 創建時間 換成當前時間,,,放出時間 跟入時間 跟入人 放出人----全不要 // 格式如上 // System.out.print(result[i][j]+"\t\t"); if (j == 0) // 編碼 pro.setpId(result[i][j]); if (j == 1) // 名字 pro.setName(result[i][j]); if (j == 2) // 類別 pro.setpList(Integer.parseInt(result[i][j])); if (j == 3) // 商品規格 pro.setPsID(result[i][j]); if (j == 4)// 單位 pro.setpUtilId(Integer.parseInt(result[i][j])); if (j == 5)// 出售價格 pro.setPrice(Double.parseDouble(result[i][j])); if (j == 6) // 進貨價格 pro.setStockPrice(Double.parseDouble(result[i][j])); if (j == 7)// 最低價格 pro.setLowestPrice(Double.parseDouble(result[i][j])); if (j == 8)// 備注 pro.setRemark(result[i][j]); } pro.setUserId(user.getUser_Id()); proList.add(pro); // crmService.saveCrmUser(crm); } return proList; } }
