Excel2003.java
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URLEncoder; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletResponse; 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.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFCell; import com.nufront.euht.excel.imports.interfaces.ExcelInterface; import com.nufront.euht.excel.util.ExcelCellStyle; import com.nufront.euht.excel.util.ExcelColor; import com.nufront.euht.excel.util.ExcelFont; import com.nufront.euht.model.CapEbu; import com.nufront.euht.model.CapEdu; import com.nufront.euht.model.TrainLine; import com.nufront.euht.pageModel.JsonTipMessage; import com.nufront.euht.util.StringUtil; public class Excel2003 implements ExcelInterface{ private StringBuffer errorMessage = new StringBuffer(); private DecimalFormat decimalFormat = new DecimalFormat("0");// 格式化 number String private final int headFontSize = 16; //Excel表头字体大小 private final int bodyFontSize = 12; //Excel主体内容字体大小 @Override public void exportExcel(HttpServletResponse response,List<TrainLine> lines , String strSheetName, String strFileName) throws IOException { //1 定义变量 OutputStream out = response.getOutputStream(); HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet(strSheetName); //2设置表头 Row rowHead = sheet.createRow(0); rowHead.setHeight((short)400); //单元格高度 for(int i = 0 ; i < tabelHeadName.length ; i++){ sheet.setColumnWidth(i, 22*256); // 设置单元格的宽度,setColumnWidth(列的位置,列的宽度) Cell cell = rowHead.createCell(i); cell.setCellValue(tabelHeadName[i]); //设置单元格样式 HSSFCellStyle headStyle = ExcelColor.cyan(workbook); //设置单元格为青色 ExcelCellStyle.CellStyle1(headStyle); //设置单元格 上下左右都为实体黑色的线条 ExcelFont.font1(workbook, headStyle, headFontSize, true);//设置设置单元格内字体样式 , 宋体 大小14 加粗 cell.setCellStyle(headStyle); } // 3 设置主体内容 int rowNumber = 0; if (lines != null && lines.size() > 0){ for(int i = 0; i < lines.size() ; i++) { TrainLine line = lines.get(i); int lineChildren = 0; ArrayList<Integer> regionReapeatCountList = new ArrayList<Integer>(); int regionReapeatCount = 1; String preRegion = "xxx"; List<CapEdu> edus = line.getCapEduList(); for (int j = 0; j < edus.size(); j++) { CapEdu edu = edus.get(j); List<CapEbu> ebus = edu.getCapEbuList(); int eduChildren = 0; for (int k = 0; k < ebus.size(); k++) { rowNumber++; eduChildren++; lineChildren++; Row rowBody = sheet.createRow(rowNumber); rowBody.setHeight((short)300); //单元格高度 for (int col = 0 ; col < tabelHeadName.length; col++) { Cell cell = rowBody.createCell(col); //设置单元格样式 HSSFCellStyle bodyStyle = ExcelColor.yellow(workbook); //设置单元格为黄色 //sheet.setColumnWidth(col, 30*256); // 设置单元格的宽度,setColumnWidth(列的位置,列的宽度) ExcelCellStyle.CellStyle1(bodyStyle); //设置单元格 上下左右都为实体黑色的线条 ExcelFont.font1(workbook, bodyStyle, bodyFontSize, false);//设置设置单元格内字体样式 , 宋体 大小14 加粗 cell.setCellStyle(bodyStyle); cell.setCellValue(getValue(line, j, k, col)); //System.out.println(getValue(line, j, k, col)); } // 记录区间的重复出现情况 String currentRegion = getValue(line, j, k, COL_REGION); if (preRegion.equals(currentRegion)) { regionReapeatCount++; } else { regionReapeatCountList.add(regionReapeatCount); regionReapeatCount = 1; if (!StringUtil.isNullOrBlank(currentRegion)) preRegion = currentRegion; else preRegion = "xxx"; } } //edu合并单元格 if (eduChildren > 1) { ExcelCellStyle.MergerCell(sheet, rowNumber-eduChildren+1, rowNumber, COL_EDU_NAME, COL_EDU_NAME); ExcelCellStyle.MergerCell(sheet, rowNumber-eduChildren+1, rowNumber, COL_EDU_MODEL, COL_EDU_MODEL); ExcelCellStyle.MergerCell(sheet, rowNumber-eduChildren+1, rowNumber, COL_EDU_IP, COL_EDU_IP); ExcelCellStyle.MergerCell(sheet, rowNumber-eduChildren+1, rowNumber, COL_EDU_CENTER_NODE, COL_EDU_CENTER_NODE); } } //line合并单元格 if (lineChildren > 1) { ExcelCellStyle.MergerCell(sheet, rowNumber-lineChildren+1, rowNumber, COL_LINE_NO, COL_LINE_NO); ExcelCellStyle.MergerCell(sheet, rowNumber-lineChildren+1, rowNumber, COL_LINE_NAME, COL_LINE_NAME); } // 区间合并 if (regionReapeatCount > 1) { regionReapeatCountList.add(regionReapeatCount); } int row = 0; for (int index = 1; index < regionReapeatCountList.size(); index++) { // 第一次的数据没意义,跳过 int count = regionReapeatCountList.get(index); row += count; if (count > 1) { ExcelCellStyle.MergerCell(sheet, row-count+1, row, COL_REGION, COL_REGION); } } } } response.addHeader("Content-Disposition", "attachment;filename=" + new String(strFileName.getBytes("gbk"),"iso-8859-1"));//URLEncoder.encode(strFileName, "GBK")); //new String(fileName.getBytes("gbk"),"iso-8859-1") response.setContentType("application/msexcel;charset=UTF-8"); workbook.write(out); out.close(); } @Override public boolean importExcel(String excelPath, List<TrainLine> lines) { if (lines == null) lines = new ArrayList<TrainLine>(); File file = new File(excelPath); boolean isSuccess = true; HSSFWorkbook hwb; HSSFRow row = null; HSSFSheet sheet =null; try { hwb = new HSSFWorkbook(new FileInputStream(file)); sheet = hwb.getSheetAt(0); } catch (Exception e) { errorMessage.append("发生未知异常,读取excel内容失败"); isSuccess = false; e.printStackTrace(); } String preLineName = ""; String preEduName = ""; String preRegion = null; CapEdu edu = null; for (int i = sheet.getFirstRowNum()+1; i < sheet.getPhysicalNumberOfRows(); i++) { row = sheet.getRow(i); if (row == null) continue; //判断是否要新增对象 String currentLineName = getValue(row, COL_LINE_NAME); if ( !StringUtil.isNullOrBlank(currentLineName) && !preLineName.equals(currentLineName)) { TrainLine line = new TrainLine(); line.setLineName(currentLineName); lines.add(line); preLineName = currentLineName; } String currentEduName = getValue(row, COL_EDU_NAME); if ( !StringUtil.isNullOrBlank(currentEduName) && !preEduName.equals(currentEduName)) { edu = new CapEdu(); edu.setEduName(currentEduName); TrainLine line = lines.get(lines.size()-1); line.getCapEduList().add(edu); preEduName = currentEduName; edu.setEduModel(getValue(row, COL_EDU_MODEL)); edu.setEduIp(getValue(row, COL_EDU_IP)); edu.setIsCenterNode((short) ("是".equals(getValue(row, COL_EDU_CENTER_NODE))? 1:0)); } CapEbu ebu = new CapEbu(); ebu.setEbuCode(getValue(row, COL_EBU_CODE)); ebu.setLocation(getValue(row, COL_EBU_LOCATION)); ebu.setHardwareVersion(getValue(row, COL_EBU_HARDWARE_VERSION)); ebu.setEbuIp(getValue(row, COL_EBU_IP)); ebu.setEbuMac(getValue(row, COL_EBU_MAC)); // 保存上一次结果,合并单元格只能在首行读数据 String region = getValue(row, COL_REGION); if (region != null) { preRegion = region; ebu.setRegion(region); } else { ebu.setRegion(preRegion); } edu.getCapEbuList().add(ebu); } return isSuccess; } @Override public JsonTipMessage importExcel(InputStream is, List<TrainLine> lines) { JsonTipMessage jsonTip = new JsonTipMessage(); if (lines == null) lines = new ArrayList<TrainLine>(); HSSFWorkbook hwb; HSSFRow row = null; HSSFSheet sheet =null; try { hwb = new HSSFWorkbook(is); sheet = hwb.getSheetAt(0); } catch (Exception e) { jsonTip.setMsg("发生未知异常,读取excel内容失败"); jsonTip.setSuccess(false); e.printStackTrace(); } // 检查表头 row = sheet.getRow(0); for (int i = 0; i< tabelHeadName.length; i++) { if (!tabelHeadName[i].equals(getValue(row, i))) { jsonTip.setErrorMsg("表格模板不正确,请在下载最新模板"); return jsonTip; } } String preLineName = ""; String preEduName = ""; String preRegion = null; CapEdu edu = null; for (int i = sheet.getFirstRowNum()+1; i < sheet.getPhysicalNumberOfRows(); i++) { row = sheet.getRow(i); if (row == null) continue; //判断是否要新增对象 String currentLineName = getValue(row, COL_LINE_NAME); String currentLineCode = getValue(row, COL_LINE_NO); if ( !StringUtil.isNullOrBlank(currentLineName) && !preLineName.equals(currentLineName)) { TrainLine line = new TrainLine(); line.setLineName(currentLineName); line.setLineCode(currentLineCode); lines.add(line); preLineName = currentLineName; } String currentEduName = getValue(row, COL_EDU_NAME); if ( !StringUtil.isNullOrBlank(currentEduName) && !preEduName.equals(currentEduName)) { edu = new CapEdu(); edu.setEduName(currentEduName); TrainLine line = lines.get(lines.size()-1); line.getCapEduList().add(edu); preEduName = currentEduName; edu.setEduModel(getValue(row, COL_EDU_MODEL)); edu.setEduIp(getValue(row, COL_EDU_IP)); edu.setIsCenterNode((short) ("是".equals(getValue(row, COL_EDU_CENTER_NODE))? 1:0)); } CapEbu ebu = new CapEbu(); ebu.setEbuCode(getValue(row, COL_EBU_CODE)); ebu.setLocation(getValue(row, COL_EBU_LOCATION)); ebu.setHardwareVersion(getValue(row, COL_EBU_HARDWARE_VERSION)); ebu.setEbuIp(getValue(row, COL_EBU_IP)); ebu.setEbuMac(getValue(row, COL_EBU_MAC)); // 保存上一次结果,合并单元格只能在首行读数据 String region = getValue(row, COL_REGION); if (region != null) { preRegion = region; ebu.setRegion(region); } else { ebu.setRegion(preRegion); } edu.getCapEbuList().add(ebu); } jsonTip.setSuccess(true); return jsonTip; } public String getValue(HSSFRow row, int column) { HSSFCell cell = row.getCell(column); String value = null; if (cell == null) return null; if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING){ value = cell.getStringCellValue(); } else if (cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC){ value = decimalFormat.format(cell.getNumericCellValue()); } return value; } public static String getValue(TrainLine line, int eduIndex, int ebuIndex, int Column) { CapEdu edu = line.getCapEduList().get(eduIndex); CapEbu ebu = edu.getCapEbuList().get(ebuIndex); String value = null; switch (Column) { case COL_LINE_NO: value = line.getLineCode(); break; case COL_LINE_NAME: value = line.getLineName(); break; case COL_EDU_NAME: value = edu.getEduName(); break; case COL_EDU_MODEL: value = edu.getEduModel(); break; case COL_EDU_CENTER_NODE: if (edu.getIsCenterNode() == 0) value = "否"; else value = "是"; break; case COL_EDU_IP: value = edu.getEduIp(); break; case COL_EBU_CODE: value = ebu.getEbuCode(); break; case COL_EBU_LOCATION: value = ebu.getLocation(); break; case COL_EBU_HARDWARE_VERSION: value = ebu.getHardwareVersion(); break; case COL_EBU_IP: value = ebu.getEbuIp(); break; case COL_EBU_MAC: value = ebu.getEbuMac(); break; case COL_REGION: value = ebu.getRegion(); break; } return value; } public StringBuffer getErrorMessage() { return errorMessage; } }
import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.util.CellRangeAddress; public class ExcelCellStyle { //单元格 上下左右都为实体黑色的线条 public static void CellStyle1(CellStyle style){ //下边框 style.setBorderBottom(CellStyle.SOLID_FOREGROUND); style.setBottomBorderColor(IndexedColors.BLACK.getIndex());//黑色 //上边框 style.setBorderTop(CellStyle.SOLID_FOREGROUND); style.setTopBorderColor(IndexedColors.BLACK.getIndex()); //左边框 style.setBorderLeft(CellStyle.SOLID_FOREGROUND); style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); //右边框 style.setBorderRight(CellStyle.SOLID_FOREGROUND); style.setRightBorderColor(IndexedColors.BLACK.getIndex()); //居中 style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直 style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平 } //合并单元格 public static void MergerCell(HSSFSheet sheet,int fristRow,int lastRow,int fristCol,int lastCol){ CellRangeAddress cra=new CellRangeAddress(fristRow,lastRow,fristCol,lastCol); sheet.addMergedRegion(cra); } }
import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.HSSFColor; public class ExcelFont { //设置单元格内字体样式 //宋体 大小14 加粗 public static void font1(HSSFWorkbook wb ,HSSFCellStyle style,int size,boolean BOLD){ HSSFFont font=wb.createFont(); font.setColor(HSSFColor.BLACK.index);//HSSFColor.VIOLET.index //字体颜色 font.setFontHeightInPoints((short)size); if(BOLD){ //是否加粗 font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); }else{ font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL); } //把字体应用到当前的样式 style.setFont(font); } }
import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.IndexedColors; public class ExcelColor { //青色 public static HSSFCellStyle cyan(HSSFWorkbook workbook){ HSSFCellStyle cyan_style = workbook.createCellStyle(); cyan_style.setFillForegroundColor(IndexedColors.SKY_BLUE.getIndex()); cyan_style.setFillPattern(CellStyle.SOLID_FOREGROUND); return cyan_style; } //黄色 public static HSSFCellStyle yellow(HSSFWorkbook workbook){ HSSFCellStyle yellow_style = workbook.createCellStyle(); yellow_style.setFillForegroundColor(IndexedColors.LIGHT_YELLOW.getIndex()); yellow_style.setFillPattern(CellStyle.SOLID_FOREGROUND); return yellow_style; } }