您的位置:首页 > 运维架构 > Apache

Apache POI Copy Cell

2015-08-15 22:35 579 查看
使用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 block
e.printStackTrace();
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: