Как сделать стиль, скопированный из исходного файла xlsx, таким же, как стиль целевого файла xlsx? ⇐ JAVA
-
Гость
Как сделать стиль, скопированный из исходного файла xlsx, таким же, как стиль целевого файла xlsx?
erryone. Вот с этой проблемой я столкнулся. Разделение нескольких страниц листов в формате xlsx на несколько файлов xlsx, содержащих только одну страницу листа, с использованием POI-OOXML 4.1.2 приводит к несовместимым стилям при копировании. Как решить эту проблему? это исходный файл xlsx: исходное изображение это целевой файл xlsx: целевое изображение Разница между двумя картинками в том, что цвета заливки разные. Ожидаемый цвет заливки — это исходное изображение. Цвет заливки для первой и второй строк исходного изображения — RGB HEX F4B7BE, а RGB HEX целевого изображения — C6E0B4. Они разные. это моя копия кода cellStyle:
... targetStyle = (XSSFCellStyle) targetWorkbook.createCellStyle(); targetStyle.cloneStyleFrom(sourceStyle); copyFont(((XSSFCellStyle) sourceStyle).getFont(), ((XSSFCellStyle) targetStyle).getFont(), targetStyle);
Каков ожидаемый цвет заливки исходного изображения. я попытался скопировать стиль, используя следующий код:
targetStyle.cloneStyleFrom(sourceStyle); XSSFColor sourceFillForegroundXSSFColor = ((XSSFCellStyle) sourceStyle).getFillForegroundXSSFColor(); XSSFColor sourceFillBackgroundXSSFColor = ((XSSFCellStyle) sourceStyle).getFillBackgroundXSSFColor(); ((XSSFCellStyle) targetStyle).setFillForegroundColor(sourceFillForegroundXSSFColor); ((XSSFCellStyle) targetStyle).setFillBackgroundColor(sourceFillBackgroundXSSFColor); targetStyle.setFillPattern(sourceStyle.getFillPattern()); Это не сработало. вот весь мой код: `
import org.apache.commons.lang3.StringUtils; импортировать org.apache.poi.EncryptedDocumentException; импортировать org.apache.poi.hssf.usermodel.HSSFCellStyle; импортировать org.apache.poi.hssf.usermodel.HSSFFont; импортировать org.apache.poi.hssf.usermodel.HSSFWorkbook; импортировать org.apache.poi.ss.usermodel.*; импортировать org.apache.poi.ss.util.CellRangeAddress; импортировать org.apache.poi.xssf.usermodel.XSSFCellStyle; импортировать org.apache.poi.xssf.usermodel.XSSFFont; импортировать org.apache.poi.xssf.usermodel.XSSFWorkbook; импортировать java.io.File; импортировать java.io.FileInputStream; импортировать java.io.FileOutputStream; импортировать java.io.IOException; импортировать java.util.ArrayList; импортировать java.util.HashMap; импортировать java.util.List; импортировать java.util.Map; импортировать java.util.regex.Matcher; импортировать java.util.regex.Pattern; общественный класс ExcelSplitterUtil { частный окончательный статический Map styleCacheLocal = new HashMap(); частная конечная статическая строка excelFileType = ".xlsx"; public static void main(String[] args) { String inputFilePath = "C:\\Users\\15206\\Desktop\\excel_sheet\\test3\\xlsx文件样式测试1.xlsx"; Строка выводаFolderPath = "C:\\Users\\15206\\Desktop\\excel_sheet\\test3\\target\\"; excelSplitter (inputFilePath, outputFolderPath); } public static void excelSplitter(String inputFilePath, String outputFolderPath) { попробуйте (FileInputStream fileInputStream = новый FileInputStream (inputFilePath)) { Источник рабочей книгиWorkbook; если (inputFilePath.endsWith(".xlsx")) { sourceWorkbook = новый XSSFWorkbook (fileInputStream); } else if (inputFilePath.endsWith(".xls")) { sourceWorkbook = новая HSSFWorkbook (fileInputStream); } еще { возвращаться; } for (intsheetIndex = 0;sheetIndex createAndCacheStyle(sourceStyle, sourceWorkbook, targetWorkbook, excelFileType)); } еще { return createAndCacheStyle(sourceStyle, sourceWorkbook, targetWorkbook, excelFileType); } } частный статический CellStyle createAndCacheStyle (CellStyle sourceStyle, Workbook sourceWorkbook, Workbook targetWorkbook, String excelFileType) { CellStyle targetStyle = null; if (excelFileType.equals(".xlsx") && sourceStyle экземпляр XSSFCellStyle) { //Исходный файл Excel — xlsx, целевой — xlsx targetStyle = (XSSFCellStyle) targetWorkbook.createCellStyle(); //Копируем основные свойства стиля targetStyle.cloneStyleFrom(sourceStyle); //Копируем шрифт copyFont(((XSSFCellStyle) sourceStyle).getFont(), ((XSSFCellStyle) targetStyle).getFont(), targetStyle); } else if (excelFileType.equals(".xlsx") && sourceStyle instanceof HSSFCellStyle) { //Исходный файл Excel — xls, целевой — xlsx targetStyle = (XSSFCellStyle) targetWorkbook.createCellStyle(); //Копируем другие свойства стиля manualCloneStyle (targetStyle, sourceStyle); //Копируем шрифт HSSFFont sourceFont = (HSSFFont) sourceWorkbook.getFontAt(sourceStyle.getFontIndexAsInt()); copyFont(sourceFont, ((XSSFCellStyle) targetStyle).getFont(), targetStyle); } else if (excelFileType.equals(".xls") && sourceStyle экземпляр XSSFCellStyle) { //Исходный файл Excel — xlsx, целевой — xls targetStyle = (HSSFCellStyle) targetWorkbook.createCellStyle(); // Копируем несовместимые стили вручную manualCloneStyle (targetStyle, sourceStyle); //Копируем шрифт copyFont(((XSSFCellStyle) sourceStyle).getFont(), ((HSSFCellStyle) targetStyle).getFont(targetWorkbook), targetStyle); } else if (excelFileType.equals(".xls") && sourceStyle instanceof HSSFCellStyle) { //Исходный файл Excel — xls, целевой — xls targetStyle = (HSSFCellStyle) targetWorkbook.createCellStyle(); //Копируем основные свойства стиля targetStyle.cloneStyleFrom(sourceStyle); //Копируем шрифт copyFont(((HSSFCellStyle) sourceStyle).getFont(sourceWorkbook), ((HSSFCellStyle) targetStyle).getFont(targetWorkbook), targetStyle); } еще { System.out.println("Тип файла excelFileType не соответствует"); вернуть ноль; } Карта workbookStyles = новый HashMap(); workbookStyles.put(System.identityHashCode(targetWorkbook), targetStyle); styleCacheLocal.put(Integer.valueOf(sourceStyle.getIndex()), workbookStyles); вернуть целевой стиль; } Private static void manualCloneStyle (CellStyle targetStyle, CellStyle sourceStyle) { targetStyle.setAlignment(sourceStyle.getAlignment()); targetStyle.setVerticalAlignment(sourceStyle.getVerticalAlignment()); targetStyle.setWrapText(sourceStyle.getWrapText()); targetStyle.setDataFormat(sourceStyle.getDataFormat()); targetStyle.setFillForegroundColor(sourceStyle.getFillForegroundColor()); targetStyle.setFillBackgroundColor(sourceStyle.getFillBackgroundColor()); targetStyle.setFillPattern(sourceStyle.getFillPattern()); targetStyle.setHidden(sourceStyle.getHidden()); targetStyle.setIndention(sourceStyle.getIndention()); targetStyle.setLocked(sourceStyle.getLocked()); targetStyle.setRotation(sourceStyle.getRotation()); targetStyle.setBorderBottom(sourceStyle.getBorderBottom()); targetStyle.setBorderLeft(sourceStyle.getBorderLeft()); targetStyle.setBorderRight(sourceStyle.getBorderRight()); targetStyle.setBorderTop(sourceStyle.getBorderTop()); targetStyle.setTopBorderColor(sourceStyle.getTopBorderColor()); targetStyle.setBottomBorderColor(sourceStyle.getBottomBorderColor()); targetStyle.setLeftBorderColor(sourceStyle.getLeftBorderColor()); targetStyle.setQuotePrefixed(sourceStyle.getQuotePrefixed()); targetStyle.setShrinkToFit(sourceStyle.getShrinkToFit()); } Private static void copyFont (Font sourceFont, Font targetFont, CellStyle cellStyle) { targetFont.setFontName(sourceFont.getFontName()); targetFont.setFontHeightInPoints(sourceFont.getFontHeightInPoints()); targetFont.setBold(sourceFont.getBold()); targetFont.setItalic(sourceFont.getItalic()); если (targetFont экземпляр XSSFFont) { если (sourceFont экземпляр XSSFFont) { ((XSSFFont) targetFont).setColor(((XSSFFont) sourceFont).getXSSFColor()); } Еще если (sourceFont экземпляр HSSFFont) { ((XSSFFont) targetFont).setColor(sourceFont.getColor()); } } еще { если (sourceFont экземпляр XSSFFont) { ((HSSFFont) targetFont).setColor(sourceFont.getColor()); } Еще если (sourceFont экземпляр HSSFFont) { ((HSSFFont) targetFont).setColor(sourceFont.getColor()); } } // 设置新字体到新样式 cellStyle.setFont(targetFont); } Private static void setCellValue(Cell targetCell, Cell sourceCell) { переключатель (sourceCell.getCellType()) { случай STRING: targetCell.setCellValue(sourceCell.getStringCellValue()); перерыв; случай ЦИФРОВОЙ: если (DateUtil.isCellDateFormatted(sourceCell)) { targetCell.setCellValue(sourceCell.getDateCellValue()); } еще { targetCell.setCellValue(sourceCell.getNumericCellValue()); } перерыв; случай БУЛЕВОЕ значение: targetCell.setCellValue(sourceCell.getBooleanCellValue()); перерыв; ФОРМУЛА случая: targetCell.setCellFormula(sourceCell.getCellFormula()); перерыв; по умолчанию: targetCell.setCellValue(sourceCell.toString()); перерыв; } } частное статическое логическое значение isMergedRegionOverlapping(CellRangeAddress newMergedRegion, Sheet targetSheet) { for (int i = 0; i
erryone. Вот с этой проблемой я столкнулся. Разделение нескольких страниц листов в формате xlsx на несколько файлов xlsx, содержащих только одну страницу листа, с использованием POI-OOXML 4.1.2 приводит к несовместимым стилям при копировании. Как решить эту проблему? это исходный файл xlsx: исходное изображение это целевой файл xlsx: целевое изображение Разница между двумя картинками в том, что цвета заливки разные. Ожидаемый цвет заливки — это исходное изображение. Цвет заливки для первой и второй строк исходного изображения — RGB HEX F4B7BE, а RGB HEX целевого изображения — C6E0B4. Они разные. это моя копия кода cellStyle:
... targetStyle = (XSSFCellStyle) targetWorkbook.createCellStyle(); targetStyle.cloneStyleFrom(sourceStyle); copyFont(((XSSFCellStyle) sourceStyle).getFont(), ((XSSFCellStyle) targetStyle).getFont(), targetStyle);
Каков ожидаемый цвет заливки исходного изображения. я попытался скопировать стиль, используя следующий код:
targetStyle.cloneStyleFrom(sourceStyle); XSSFColor sourceFillForegroundXSSFColor = ((XSSFCellStyle) sourceStyle).getFillForegroundXSSFColor(); XSSFColor sourceFillBackgroundXSSFColor = ((XSSFCellStyle) sourceStyle).getFillBackgroundXSSFColor(); ((XSSFCellStyle) targetStyle).setFillForegroundColor(sourceFillForegroundXSSFColor); ((XSSFCellStyle) targetStyle).setFillBackgroundColor(sourceFillBackgroundXSSFColor); targetStyle.setFillPattern(sourceStyle.getFillPattern()); Это не сработало. вот весь мой код: `
import org.apache.commons.lang3.StringUtils; импортировать org.apache.poi.EncryptedDocumentException; импортировать org.apache.poi.hssf.usermodel.HSSFCellStyle; импортировать org.apache.poi.hssf.usermodel.HSSFFont; импортировать org.apache.poi.hssf.usermodel.HSSFWorkbook; импортировать org.apache.poi.ss.usermodel.*; импортировать org.apache.poi.ss.util.CellRangeAddress; импортировать org.apache.poi.xssf.usermodel.XSSFCellStyle; импортировать org.apache.poi.xssf.usermodel.XSSFFont; импортировать org.apache.poi.xssf.usermodel.XSSFWorkbook; импортировать java.io.File; импортировать java.io.FileInputStream; импортировать java.io.FileOutputStream; импортировать java.io.IOException; импортировать java.util.ArrayList; импортировать java.util.HashMap; импортировать java.util.List; импортировать java.util.Map; импортировать java.util.regex.Matcher; импортировать java.util.regex.Pattern; общественный класс ExcelSplitterUtil { частный окончательный статический Map styleCacheLocal = new HashMap(); частная конечная статическая строка excelFileType = ".xlsx"; public static void main(String[] args) { String inputFilePath = "C:\\Users\\15206\\Desktop\\excel_sheet\\test3\\xlsx文件样式测试1.xlsx"; Строка выводаFolderPath = "C:\\Users\\15206\\Desktop\\excel_sheet\\test3\\target\\"; excelSplitter (inputFilePath, outputFolderPath); } public static void excelSplitter(String inputFilePath, String outputFolderPath) { попробуйте (FileInputStream fileInputStream = новый FileInputStream (inputFilePath)) { Источник рабочей книгиWorkbook; если (inputFilePath.endsWith(".xlsx")) { sourceWorkbook = новый XSSFWorkbook (fileInputStream); } else if (inputFilePath.endsWith(".xls")) { sourceWorkbook = новая HSSFWorkbook (fileInputStream); } еще { возвращаться; } for (intsheetIndex = 0;sheetIndex createAndCacheStyle(sourceStyle, sourceWorkbook, targetWorkbook, excelFileType)); } еще { return createAndCacheStyle(sourceStyle, sourceWorkbook, targetWorkbook, excelFileType); } } частный статический CellStyle createAndCacheStyle (CellStyle sourceStyle, Workbook sourceWorkbook, Workbook targetWorkbook, String excelFileType) { CellStyle targetStyle = null; if (excelFileType.equals(".xlsx") && sourceStyle экземпляр XSSFCellStyle) { //Исходный файл Excel — xlsx, целевой — xlsx targetStyle = (XSSFCellStyle) targetWorkbook.createCellStyle(); //Копируем основные свойства стиля targetStyle.cloneStyleFrom(sourceStyle); //Копируем шрифт copyFont(((XSSFCellStyle) sourceStyle).getFont(), ((XSSFCellStyle) targetStyle).getFont(), targetStyle); } else if (excelFileType.equals(".xlsx") && sourceStyle instanceof HSSFCellStyle) { //Исходный файл Excel — xls, целевой — xlsx targetStyle = (XSSFCellStyle) targetWorkbook.createCellStyle(); //Копируем другие свойства стиля manualCloneStyle (targetStyle, sourceStyle); //Копируем шрифт HSSFFont sourceFont = (HSSFFont) sourceWorkbook.getFontAt(sourceStyle.getFontIndexAsInt()); copyFont(sourceFont, ((XSSFCellStyle) targetStyle).getFont(), targetStyle); } else if (excelFileType.equals(".xls") && sourceStyle экземпляр XSSFCellStyle) { //Исходный файл Excel — xlsx, целевой — xls targetStyle = (HSSFCellStyle) targetWorkbook.createCellStyle(); // Копируем несовместимые стили вручную manualCloneStyle (targetStyle, sourceStyle); //Копируем шрифт copyFont(((XSSFCellStyle) sourceStyle).getFont(), ((HSSFCellStyle) targetStyle).getFont(targetWorkbook), targetStyle); } else if (excelFileType.equals(".xls") && sourceStyle instanceof HSSFCellStyle) { //Исходный файл Excel — xls, целевой — xls targetStyle = (HSSFCellStyle) targetWorkbook.createCellStyle(); //Копируем основные свойства стиля targetStyle.cloneStyleFrom(sourceStyle); //Копируем шрифт copyFont(((HSSFCellStyle) sourceStyle).getFont(sourceWorkbook), ((HSSFCellStyle) targetStyle).getFont(targetWorkbook), targetStyle); } еще { System.out.println("Тип файла excelFileType не соответствует"); вернуть ноль; } Карта workbookStyles = новый HashMap(); workbookStyles.put(System.identityHashCode(targetWorkbook), targetStyle); styleCacheLocal.put(Integer.valueOf(sourceStyle.getIndex()), workbookStyles); вернуть целевой стиль; } Private static void manualCloneStyle (CellStyle targetStyle, CellStyle sourceStyle) { targetStyle.setAlignment(sourceStyle.getAlignment()); targetStyle.setVerticalAlignment(sourceStyle.getVerticalAlignment()); targetStyle.setWrapText(sourceStyle.getWrapText()); targetStyle.setDataFormat(sourceStyle.getDataFormat()); targetStyle.setFillForegroundColor(sourceStyle.getFillForegroundColor()); targetStyle.setFillBackgroundColor(sourceStyle.getFillBackgroundColor()); targetStyle.setFillPattern(sourceStyle.getFillPattern()); targetStyle.setHidden(sourceStyle.getHidden()); targetStyle.setIndention(sourceStyle.getIndention()); targetStyle.setLocked(sourceStyle.getLocked()); targetStyle.setRotation(sourceStyle.getRotation()); targetStyle.setBorderBottom(sourceStyle.getBorderBottom()); targetStyle.setBorderLeft(sourceStyle.getBorderLeft()); targetStyle.setBorderRight(sourceStyle.getBorderRight()); targetStyle.setBorderTop(sourceStyle.getBorderTop()); targetStyle.setTopBorderColor(sourceStyle.getTopBorderColor()); targetStyle.setBottomBorderColor(sourceStyle.getBottomBorderColor()); targetStyle.setLeftBorderColor(sourceStyle.getLeftBorderColor()); targetStyle.setQuotePrefixed(sourceStyle.getQuotePrefixed()); targetStyle.setShrinkToFit(sourceStyle.getShrinkToFit()); } Private static void copyFont (Font sourceFont, Font targetFont, CellStyle cellStyle) { targetFont.setFontName(sourceFont.getFontName()); targetFont.setFontHeightInPoints(sourceFont.getFontHeightInPoints()); targetFont.setBold(sourceFont.getBold()); targetFont.setItalic(sourceFont.getItalic()); если (targetFont экземпляр XSSFFont) { если (sourceFont экземпляр XSSFFont) { ((XSSFFont) targetFont).setColor(((XSSFFont) sourceFont).getXSSFColor()); } Еще если (sourceFont экземпляр HSSFFont) { ((XSSFFont) targetFont).setColor(sourceFont.getColor()); } } еще { если (sourceFont экземпляр XSSFFont) { ((HSSFFont) targetFont).setColor(sourceFont.getColor()); } Еще если (sourceFont экземпляр HSSFFont) { ((HSSFFont) targetFont).setColor(sourceFont.getColor()); } } // 设置新字体到新样式 cellStyle.setFont(targetFont); } Private static void setCellValue(Cell targetCell, Cell sourceCell) { переключатель (sourceCell.getCellType()) { случай STRING: targetCell.setCellValue(sourceCell.getStringCellValue()); перерыв; случай ЦИФРОВОЙ: если (DateUtil.isCellDateFormatted(sourceCell)) { targetCell.setCellValue(sourceCell.getDateCellValue()); } еще { targetCell.setCellValue(sourceCell.getNumericCellValue()); } перерыв; случай БУЛЕВОЕ значение: targetCell.setCellValue(sourceCell.getBooleanCellValue()); перерыв; ФОРМУЛА случая: targetCell.setCellFormula(sourceCell.getCellFormula()); перерыв; по умолчанию: targetCell.setCellValue(sourceCell.toString()); перерыв; } } частное статическое логическое значение isMergedRegionOverlapping(CellRangeAddress newMergedRegion, Sheet targetSheet) { for (int i = 0; i
Мобильная версия