Apache POI Copy Cell

来源:互联网 发布:总钥匙系统知乎 编辑:程序博客网 时间:2024/05/06 23:48

使用Java操作Excel表格,复制表格的功能。

import java.io.IOException;import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.ss.usermodel.CellStyle;import org.apache.poi.ss.usermodel.CreationHelper;import org.apache.poi.ss.usermodel.DateUtil;import org.apache.poi.ss.usermodel.Font;import org.apache.poi.ss.usermodel.Hyperlink;import org.apache.poi.ss.usermodel.IndexedColors;import org.apache.poi.ss.usermodel.Workbook;public class ExcelTool {private CreationHelper helper = null;private Workbook wb = null;public ExcelTool(Workbook workbook) {this.wb = workbook;this.helper = workbook.getCreationHelper();}// 单元格复制函数public void copyCell(Cell oldCell, Cell newCell) {CellStyle newStyle = this.wb.createCellStyle();copyStyle(oldCell.getCellStyle(), newStyle);newCell.setCellStyle(newStyle);// 评论if (oldCell.getCellComment() != null) {newCell.setCellComment(oldCell.getCellComment());}// 对日期和超链接进行了处理switch (oldCell.getCellType()) {case Cell.CELL_TYPE_BLANK:newCell.setCellType(Cell.CELL_TYPE_BLANK);break;case Cell.CELL_TYPE_BOOLEAN:newCell.setCellValue(oldCell.getBooleanCellValue());break;case Cell.CELL_TYPE_ERROR:newCell.setCellErrorValue(oldCell.getErrorCellValue());break;case Cell.CELL_TYPE_FORMULA:newCell.setCellFormula(oldCell.getCellFormula());break;case Cell.CELL_TYPE_NUMERIC:if (DateUtil.isCellDateFormatted(oldCell)) {newCell.setCellValue(oldCell.getDateCellValue());} else {newCell.setCellValue(oldCell.getNumericCellValue());}break;case Cell.CELL_TYPE_STRING:newCell.setCellValue(oldCell.getRichStringCellValue());if (oldCell.getHyperlink() != null) {Font hlink_font = this.wb.createFont();hlink_font.setUnderline(Font.U_SINGLE);hlink_font.setColor(IndexedColors.BLUE.getIndex());Hyperlink link = helper.createHyperlink(Hyperlink.LINK_URL);link.setAddress(oldCell.getHyperlink().getAddress());newCell.setHyperlink(link);newCell.getCellStyle().setFont(hlink_font);}break;}}// 单元格样式复制函数private void copyStyle(CellStyle oldStyle, CellStyle newStyle) {newStyle.setAlignment(oldStyle.getAlignment());newStyle.setDataFormat(oldStyle.getDataFormat());newStyle.setFillPattern(oldStyle.getFillPattern());newStyle.setHidden(oldStyle.getHidden());newStyle.setLocked(oldStyle.getLocked());newStyle.setIndention(oldStyle.getIndention());newStyle.setRotation(oldStyle.getRotation());newStyle.setVerticalAlignment(oldStyle.getVerticalAlignment());newStyle.setWrapText(oldStyle.getWrapText());}public void close() {try {this.wb.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}


0 0
原创粉丝点击