java 讀Excel中內容寫入到word中
阿新 • • 發佈:2018-12-10
Excel2WordUtil 類
import java.awt.Color; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.ClientAnchor; import org.apache.poi.ss.usermodel.PictureData; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.Font; import com.lowagie.text.Image; import com.lowagie.text.PageSize; import com.lowagie.text.Paragraph; import com.lowagie.text.Table; import com.lowagie.text.pdf.BaseFont; import com.lowagie.text.rtf.RtfWriter2; /** * */ public class Excel2WordUtil { public static void main(String[] args) { String excelPath = "C:\\temp1.xls"; String wordPath = "C:\\a.doc"; excel2Word(excelPath, wordPath); String path = "d:\\"; File file = new File(path); if (file.exists()) { if (file.isDirectory()) { File[] listFiles = file.listFiles(); for (File tempFile : listFiles) { String name = tempFile.getName(); if (name.contains("temp_") && name.endsWith("png")) { tempFile.delete(); } } } } } public static void excel2Word(String excelPath, String wordPath) { Workbook wb = ReadExcelUtil.createWorkbook(excelPath); FileOutputStream out = null; try { // 建立word文件,並設定紙張的大小 out = new FileOutputStream(new File(wordPath)); Document document = new Document(PageSize.A4); RtfWriter2.getInstance(document, out); document.open(); int numberOfSheets = wb.getNumberOfSheets(); List<Position> arrayList = new ArrayList<>(); for (int i = 0; i < numberOfSheets; i++) { Sheet sheet = wb.getSheetAt(i); arrayList.clear(); Map<String, String>[] map = ReadExcelUtil.getRowSpanColSpanMap(sheet); int lastRowNum = sheet.getLastRowNum(); Row row = null; for (int j = 0; j < lastRowNum; j++) { row = sheet.getRow(j); if (row != null) { break; } } short lastCellNum = 10; if (row != null) { lastCellNum = row.getLastCellNum(); } Table table = new Table(lastCellNum, lastRowNum); table.setBorderWidth(1); table.setBorderColor(Color.BLACK); table.setPadding(0); table.setSpacing(0); for (int rowNum = sheet.getFirstRowNum(); rowNum <= lastRowNum; rowNum++) { Row excelRow = sheet.getRow(rowNum); if (excelRow == null) { continue; } lastCellNum = excelRow.getLastCellNum(); int rowSpan = 1; boolean isFirst = true; short firstCellNum = excelRow.getFirstCellNum(); if (firstCellNum == -1) { break; } for (int cellNum = firstCellNum; cellNum <= lastCellNum; cellNum++) { Cell excelCell = excelRow.getCell(cellNum); if (excelCell == null) { continue; } CellStyle cellStyle = excelCell.getCellStyle(); short foregroundColorIndex = cellStyle.getFillForegroundColor(); short fontIndex = cellStyle.getFontIndex(); int colorIndex = wb.getFontAt(fontIndex).getColor(); String cellValue = ReadExcelUtil.getCellValue(excelCell); int colSpan = 1; for (Map.Entry<String, String> entry : map[0].entrySet()) { String key = entry.getKey(); String pointString = entry.getValue(); int startRowNum = Integer.valueOf(key.split(",")[0]); int startCellNum = Integer.valueOf(key.split(",")[1]); int endRow = Integer.valueOf(pointString.split(",")[0]); int endCol = Integer.valueOf(pointString.split(",")[1]); if (rowNum == startRowNum && startCellNum == cellNum) { rowSpan = endRow - startRowNum + 1; colSpan = endCol - startCellNum + 1; } } if (isCovered(arrayList, rowNum, cellNum)) { continue; } Image image = null; Map<ClientAnchor, PictureData> pictureDate = ReadExcelUtil.getPictures(sheet); if (pictureDate != null) { for (Map.Entry<ClientAnchor, PictureData> entry : pictureDate.entrySet()) { if (entry.getKey().getRow1() == rowNum && entry.getKey().getCol1() == cellNum) { PictureData pictureData = entry.getValue(); byte[] data = pictureData.getData(); String fileName = UUID.randomUUID().toString(); String name = "d:\\temp_" + fileName + ".png"; writeFile(data, name); image = Image.getInstance(name); int[] imageWH = ImageUtil.getImageWH(name, 280); image.scaleAbsolute(imageWH[0], imageWH[1]); break; } } } com.lowagie.text.Cell cell = null; if (image != null) { image.setAlignment(Image.ALIGN_CENTER);// 設定圖片顯示位置 cell = new com.lowagie.text.Cell(image);// 單元格 } else { cellValue = removeEnter(cellValue); Color color = createColorByIndex(colorIndex); Font font = createFont(color); cell = new com.lowagie.text.Cell(new Paragraph(cellValue, font));// 單元格 } cell.setColspan(colSpan); cell.setRowspan(rowSpan); Color createColorByIndex = createColorByIndex(foregroundColorIndex); cell.setBackgroundColor(createColorByIndex); // 其中1為居中對齊,2為右對齊,3為左對齊 cell.setVerticalAlignment(1); short alignment = cellStyle.getAlignment(); short borderBottom = cellStyle.getBorderBottom(); short borderLeft = cellStyle.getBorderLeft(); short borderRight = cellStyle.getBorderRight(); short borderTop = cellStyle.getBorderTop(); if (borderBottom == 0 && borderLeft == 0 && borderRight == 0 && borderTop == 0) { cell.setBorder(0); } cell.setHorizontalAlignment(alignment - 1); cell.setWidth(100); // 同一行中只新增一次空行,避免讀到下一列時重複新增空行 if (isFirst) { int nextPage = isNextPage(rowNum, rowSpan); if (nextPage != 0) { com.lowagie.text.Cell cell2 = new com.lowagie.text.Cell(""); cell2.setColspan(lastCellNum); cell2.setRowspan(nextPage); cell2.setBorder(1); table.addCell(cell2); isFirst = false; } } table.addCell(cell); if (rowSpan * colSpan != 1) { arrayList.add(new Position(rowNum, rowNum + rowSpan - 1, cellNum, cellNum + colSpan - 1)); } } } document.add(table); if (i != numberOfSheets - 1) { document.newPage(); } } document.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 通過Excel表格中顏色index獲取AWT中Color * * @param colorIndex * @return */ private static Color createColorByIndex(int colorIndex) { Map<Integer, HSSFColor> indexHash = HSSFColor.getIndexHash(); HSSFColor hssfColor = indexHash.get(colorIndex); if (hssfColor != null) { short[] triplet = hssfColor.getTriplet(); Color color = new Color(triplet[0], triplet[1], triplet[2]); return color; } return null; } /** * 去除字串中的\r\n * \r\n在word中會顯示成問號 * * @param cellValue * @return */ private static String removeEnter(String cellValue) { if (cellValue.contains("\r\n")) { StringBuilder builder = new StringBuilder(); char[] charArray = cellValue.toCharArray(); for (char c : charArray) { // 去掉換行符 if (Integer.valueOf(c) != 13) { builder.append(c); } } return builder.toString(); } else { return cellValue; } } /** * 根據顏色建立字型 * * @param color * @return * @throws DocumentException * @throws IOException */ private static Font createFont(Color color) throws DocumentException, IOException { BaseFont bfSun = BaseFont.createFont("c:\\WINDOWS\\fonts\\SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); Font font = new Font(bfSun, 11); font.setColor(color); return font; } private static void writeFile(byte[] data, String name) throws FileNotFoundException, IOException { File file = new File(name); FileOutputStream picOut = new FileOutputStream(file); picOut.write(data); picOut.close(); } /** * 判斷是否需要新增空行 * * @param startRow * 當前行號 * @param occupyRow * 當前內容所佔用的行數 * @return 需要新增空行的行數 */ private static int isNextPage(int startRow, int occupyRow) { // 每頁所佔行數,word每頁可容納Excel 52行,預設高度 int count = 52; int b = startRow / count; int endRow = startRow + occupyRow; // 當前頁最後一行行號 int i = count * (b + 1); if (endRow > i) { return i - startRow; } return 0; } private static boolean isCovered(List<Position> arrayList, int rowNum, int cellNum) { for (Position content : arrayList) { if (rowNum >= content.getStartRow() && rowNum <= content.getEndRow() && cellNum >= content.getStartCol() && cellNum <= content.getEndCol()) { return true; } } return false; } }
ReadExcelUtil
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.poi.POIXMLDocumentPart; import org.apache.poi.hssf.usermodel.HSSFClientAnchor; import org.apache.poi.hssf.usermodel.HSSFDataFormat; import org.apache.poi.hssf.usermodel.HSSFDateUtil; import org.apache.poi.hssf.usermodel.HSSFPatriarch; import org.apache.poi.hssf.usermodel.HSSFPicture; import org.apache.poi.hssf.usermodel.HSSFPictureData; import org.apache.poi.hssf.usermodel.HSSFShape; 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.CellStyle; import org.apache.poi.ss.usermodel.ClientAnchor; import org.apache.poi.ss.usermodel.PictureData; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.usermodel.XSSFDrawing; import org.apache.poi.xssf.usermodel.XSSFPicture; import org.apache.poi.xssf.usermodel.XSSFShape; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ReadExcelUtil { public static Workbook createWorkbook(String excelPath) { InputStream is = null; Workbook wb = null; try { File sourcefile = new File(excelPath); is = new FileInputStream(sourcefile); wb = WorkbookFactory.create(is); if (wb instanceof XSSFWorkbook) { wb = (XSSFWorkbook) wb; } else if (wb instanceof HSSFWorkbook) { wb = (HSSFWorkbook) wb; } } catch (Exception e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return wb; } /** * 獲取Excel中資料起始行,起始列,結束行,結束列 * * @param sheet * @return */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static Map<String, String>[] getRowSpanColSpanMap(Sheet sheet) { Map<String, String> map0 = new HashMap<String, String>(); Map<String, String> map1 = new HashMap<String, String>(); int mergedNum = sheet.getNumMergedRegions(); CellRangeAddress range = null; for (int i = 0; i < mergedNum; i++) { range = sheet.getMergedRegion(i); int topRow = range.getFirstRow(); int topCol = range.getFirstColumn(); int bottomRow = range.getLastRow(); int bottomCol = range.getLastColumn(); map0.put(topRow + "," + topCol, bottomRow + "," + bottomCol); int tempRow = topRow; while (tempRow <= bottomRow) { int tempCol = topCol; while (tempCol <= bottomCol) { map1.put(tempRow + "," + tempCol, ""); tempCol++; } tempRow++; } map1.remove(topRow + "," + topCol); } Map[] map = { map0, map1 }; return map; } /** * @param cell * @return */ public static String getCellValue(Cell cell) { String result = new String(); switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: if (HSSFDateUtil.isCellDateFormatted(cell)) { SimpleDateFormat sdf = null; if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm")) { sdf = new SimpleDateFormat("HH:mm"); } else { sdf = new SimpleDateFormat("yyyy-MM-dd"); } Date date = cell.getDateCellValue(); result = sdf.format(date); } else if (cell.getCellStyle().getDataFormat() == 58) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); double value = cell.getNumericCellValue(); Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(value); result = sdf.format(date); } else { double value = cell.getNumericCellValue(); CellStyle style = cell.getCellStyle(); DecimalFormat format = new DecimalFormat(); String temp = style.getDataFormatString(); if (temp.equals("General")) { format.applyPattern("#"); } result = format.format(value); } break; case Cell.CELL_TYPE_STRING: result = cell.getRichStringCellValue().toString(); break; case Cell.CELL_TYPE_BLANK: result = ""; break; default: result = ""; break; } return result; } /** * @param sheet * @return * @throws IOException */ public static Map<ClientAnchor, PictureData> getPictures(Sheet sheet) { Map<ClientAnchor, PictureData> map = new HashMap<ClientAnchor, PictureData>(); if (sheet instanceof XSSFSheet) { List<POIXMLDocumentPart> list = ((XSSFSheet) sheet).getRelations(); for (POIXMLDocumentPart part : list) { if (part instanceof XSSFDrawing) { XSSFDrawing drawing = (XSSFDrawing) part; List<XSSFShape> shapes = drawing.getShapes(); for (XSSFShape shape : shapes) { XSSFPicture picture = (XSSFPicture) shape; ClientAnchor anchor = picture.getPreferredSize(); map.put(anchor, picture.getPictureData()); } } } } else { HSSFPatriarch hssfPatriarch = ((HSSFSheet) sheet).getDrawingPatriarch(); if (hssfPatriarch != null) { List<HSSFShape> shapes = hssfPatriarch.getChildren(); if (shapes.size() > 0) { for (HSSFShape sp : shapes) { if (sp instanceof HSSFPicture) { HSSFPicture picture = (HSSFPicture) sp; HSSFPictureData pictureData = picture.getPictureData(); if (picture.getAnchor() instanceof HSSFClientAnchor) { HSSFClientAnchor anchor = (HSSFClientAnchor) picture.getAnchor(); map.put(anchor, pictureData); } } } } } } return map; } }
ImageUtil
import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class ImageUtil { public static int[] getImageWH(String imagePath, int width_Max) { double radio = 1; BufferedImage image = readImage(imagePath); int targetW = image.getWidth(); int targetH = image.getHeight(); if (targetW > width_Max) { radio = (double) width_Max / targetW; targetW = width_Max; targetH = (int) (targetH * radio); } return new int[] { targetW, targetH }; } public static BufferedImage readImage(final String imagePath) { final File file = new File(imagePath); BufferedImage image = null; try { image = ImageIO.read(file); } catch (final IOException e) { } return image; } }
Position
public class Position {
private int startRow;
private int endRow;
private int startCol;
private int endCol;
public Position(int startRow, int endRow, int startCol, int endCol) {
super();
this.startRow = startRow;
this.endRow = endRow;
this.startCol = startCol;
this.endCol = endCol;
}
public Position() {
}
public int getStartRow() {
return startRow;
}
public void setStartRow(int startRow) {
this.startRow = startRow;
}
public int getEndRow() {
return endRow;
}
public void setEndRow(int endRow) {
this.endRow = endRow;
}
public int getStartCol() {
return startCol;
}
public void setStartCol(int startCol) {
this.startCol = startCol;
}
public int getEndCol() {
return endCol;
}
public void setEndCol(int endCol) {
this.endCol = endCol;
}
}