Мост .xlsx → PDF: SpreadsheetML-конвейер без LibreOffice/POI #91
@@ -0,0 +1,556 @@
|
||||
package ru.pjandro.wordpdf;
|
||||
|
||||
import org.apache.poi.common.usermodel.HyperlinkType;
|
||||
import org.apache.poi.ss.usermodel.BorderStyle;
|
||||
import org.apache.poi.ss.usermodel.Cell;
|
||||
import org.apache.poi.ss.usermodel.CellStyle;
|
||||
import org.apache.poi.ss.usermodel.CellType;
|
||||
import org.apache.poi.ss.usermodel.FillPatternType;
|
||||
import org.apache.poi.ss.usermodel.Font;
|
||||
import org.apache.poi.ss.usermodel.HorizontalAlignment;
|
||||
import org.apache.poi.ss.usermodel.Hyperlink;
|
||||
import org.apache.poi.ss.usermodel.PrintSetup;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
import org.apache.poi.ss.usermodel.VerticalAlignment;
|
||||
import org.apache.poi.ss.usermodel.Workbook;
|
||||
import org.apache.poi.ss.util.CellRangeAddress;
|
||||
import org.apache.poi.xddf.usermodel.chart.AxisCrosses;
|
||||
import org.apache.poi.xddf.usermodel.chart.AxisPosition;
|
||||
import org.apache.poi.xddf.usermodel.chart.ChartTypes;
|
||||
import org.apache.poi.xddf.usermodel.chart.XDDFCategoryAxis;
|
||||
import org.apache.poi.xddf.usermodel.chart.XDDFCategoryDataSource;
|
||||
import org.apache.poi.xddf.usermodel.chart.XDDFChartData;
|
||||
import org.apache.poi.xddf.usermodel.chart.XDDFDataSourcesFactory;
|
||||
import org.apache.poi.xddf.usermodel.chart.XDDFNumericalDataSource;
|
||||
import org.apache.poi.xddf.usermodel.chart.XDDFValueAxis;
|
||||
import org.apache.poi.xssf.usermodel.XSSFCell;
|
||||
import org.apache.poi.xssf.usermodel.XSSFChart;
|
||||
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
|
||||
import org.apache.poi.xssf.usermodel.XSSFColor;
|
||||
import org.apache.poi.xssf.usermodel.XSSFDrawing;
|
||||
import org.apache.poi.xssf.usermodel.XSSFFont;
|
||||
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
|
||||
import org.apache.poi.xssf.usermodel.XSSFSheet;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell;
|
||||
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTColor;
|
||||
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbook;
|
||||
import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellType;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.Color;
|
||||
import java.awt.Graphics2D;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
/**
|
||||
* ОДНОРАЗОВАЯ утилита: генерация готовых .xlsx для тестов (Apache POI).
|
||||
*
|
||||
* Готовые файлы лежат в {@code wordpdf-core/src/test/resources/samples/}
|
||||
* и коммитятся в репозиторий: сами тесты работают с ними как с
|
||||
* обычными входными файлами и .xlsx не генерируют.
|
||||
*
|
||||
* Фикстуры покрывают контракт моста {@code internal.xlsx} (значения,
|
||||
* стили, numFmt, merge, multi-sheet, page setup, разрывы строк, рисунки
|
||||
* и диаграммы) — см. план поддержки .xlsx и {@code docs/agent/}.
|
||||
*
|
||||
* Пересоздать (если нужно):
|
||||
* <pre>
|
||||
* mvn -pl wordpdf-core test-compile \
|
||||
* -Dmdep.outputFile=/tmp/cp.txt dependency:build-classpath -q
|
||||
* java -cp wordpdf-core/target/test-classes:$(cat /tmp/cp.txt) \
|
||||
* ru.pjandro.wordpdf.SampleXlsxGenerator \
|
||||
* wordpdf-core/src/test/resources/samples
|
||||
* </pre>
|
||||
*/
|
||||
public final class SampleXlsxGenerator {
|
||||
|
||||
/** Индекс theme-цвета accent1 в color@theme (ECMA-376 §18.18.72 таблица). */
|
||||
private static final long THEME_ACCENT1 = 4;
|
||||
/** Tint 60% высветления (Excel-канonical запись 0.599993896216032). */
|
||||
private static final double TINT_60 = 0.599993896216032;
|
||||
/** Ширина столбца в единицах POI (1/256 знака): ~12 знаков. */
|
||||
private static final int COL_WIDTH_12 = 12 * 256;
|
||||
/** Число столбцов широкого листа. */
|
||||
private static final int WIDE_COLS = 40;
|
||||
/** Число строк широкого листа. */
|
||||
private static final int WIDE_ROWS = 60;
|
||||
/** Номер строки (0-based), перед которой ставится ручной разрыв. */
|
||||
private static final int WIDE_ROW_BREAK = 11;
|
||||
/** Число ручных разрывов в фикстуре лимита страниц (> MAX_PAGES=100). */
|
||||
private static final int PAGE_LIMIT_BREAKS = 130;
|
||||
|
||||
private SampleXlsxGenerator() {
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Path dir = Paths.get(args.length > 0 ? args[0] : "samples");
|
||||
dir.toFile().mkdirs();
|
||||
|
||||
basic(dir.resolve("xlsx-basic.xlsx"));
|
||||
numFmt(dir.resolve("xlsx-numfmt.xlsx"));
|
||||
dates1904(dir.resolve("xlsx-1904.xlsx"));
|
||||
wide(dir.resolve("xlsx-wide.xlsx"));
|
||||
fitToPage(dir.resolve("xlsx-fit-to-page.xlsx"));
|
||||
chartImage(dir.resolve("xlsx-chart-image.xlsx"));
|
||||
pageLimit(dir.resolve("xlsx-page-limit.xlsx"));
|
||||
|
||||
System.out.println("Готово: " + dir.toAbsolutePath());
|
||||
}
|
||||
|
||||
// ================== Фикстуры ==================
|
||||
|
||||
/**
|
||||
* Базовая: два видимых листа, кириллица+латиница, стили (b/i/u/s, цвета
|
||||
* rgb и theme-accent1, заливки solid rgb и theme+tint, границы
|
||||
* thin/medium/double/dashed, jc, vAlign, wrapText, Arial/Calibri),
|
||||
* merge B2:D2 / C5:C6 / F3:G4, числа General, shared и inlineStr,
|
||||
* булево, rich-text, гиперссылка, скрытые строка и столбец.
|
||||
*/
|
||||
private static void basic(Path out) throws Exception {
|
||||
try (XSSFWorkbook wb = new XSSFWorkbook()) {
|
||||
XSSFSheet s = wb.createSheet("Отчёт");
|
||||
CellStyle plain = wb.createCellStyle();
|
||||
|
||||
Cell a1 = cell(s, 0, 0, "Отчёт", plain);
|
||||
Hyperlink link = wb.getCreationHelper().createHyperlink(HyperlinkType.URL);
|
||||
link.setAddress("https://example.com/report");
|
||||
a1.setHyperlink(link);
|
||||
|
||||
// Заголовок B2:D2: жирный 14 Arial, центр, жёлтая заливка rgb.
|
||||
CellStyle header = wb.createCellStyle();
|
||||
Font f = wb.createFont();
|
||||
f.setBold(true);
|
||||
f.setFontHeightInPoints((short) 14);
|
||||
f.setFontName("Arial");
|
||||
header.setFont(f);
|
||||
header.setAlignment(HorizontalAlignment.CENTER);
|
||||
header.setFillForegroundColor(new XSSFColor(new byte[] {
|
||||
(byte) 0xFF, (byte) 0xFF, 0x00}, null));
|
||||
header.setFillPattern(FillPatternType.SOLID_FOREGROUND);
|
||||
mergeText(s, 1, 1, 1, 3, "Квартальные итоги", header);
|
||||
|
||||
// Шапка таблицы 4-й строки: подчёркивание, цвет rgb, зачёркивание,
|
||||
// курсив theme-accent1, правый jc.
|
||||
Font u = wb.createFont();
|
||||
u.setBold(true);
|
||||
u.setUnderline(Font.U_SINGLE);
|
||||
CellStyle stUnderline = wb.createCellStyle();
|
||||
stUnderline.setFont(u);
|
||||
Font red = wb.createFont();
|
||||
((XSSFFont) red).setColor(new XSSFColor(new byte[] {(byte) 0xFF, 0, 0}, null));
|
||||
CellStyle stRed = wb.createCellStyle();
|
||||
stRed.setFont(red);
|
||||
stRed.setBorderLeft(BorderStyle.THIN);
|
||||
stRed.setBorderBottom(BorderStyle.THIN);
|
||||
Font strike = wb.createFont();
|
||||
strike.setStrikeout(true);
|
||||
CellStyle stStrike = wb.createCellStyle();
|
||||
stStrike.setFont(strike);
|
||||
stStrike.setBorderRight(BorderStyle.DOUBLE);
|
||||
// XSSFFont.setColor(XSSFColor) теряет theme-атрибут (пишет rgb="")
|
||||
// — цвет пишется напрямую в CTFont/color (ECMA-376 §18.8.23 CT_Color).
|
||||
Font accent = wb.createFont();
|
||||
accent.setItalic(true);
|
||||
CTColor accentCt = ((XSSFFont) accent).getCTFont().addNewColor();
|
||||
accentCt.setTheme(THEME_ACCENT1);
|
||||
CellStyle stAccent = wb.createCellStyle();
|
||||
stAccent.setFont(accent);
|
||||
CellStyle stRight = wb.createCellStyle();
|
||||
stRight.setAlignment(HorizontalAlignment.RIGHT);
|
||||
|
||||
cell(s, 3, 0, "Товар", stUnderline);
|
||||
cell(s, 3, 1, "Q1", stRed);
|
||||
cell(s, 3, 2, "Q2", plain);
|
||||
cell(s, 3, 3, "Δ", stStrike);
|
||||
cell(s, 3, 4, "Заметка", stAccent);
|
||||
|
||||
// 5-я строка: число General, вертикальный merge C5:C6 с переносом,
|
||||
// булево, заливка theme-accent1+tint, inlineStr, vAlign top.
|
||||
CellStyle stTop = wb.createCellStyle();
|
||||
stTop.setVerticalAlignment(VerticalAlignment.TOP);
|
||||
cell(s, 4, 0, "Молоко", stTop);
|
||||
cell(s, 4, 1, 1234.5, plain);
|
||||
CellStyle stWrap = wb.createCellStyle();
|
||||
stWrap.setWrapText(true);
|
||||
stWrap.setVerticalAlignment(VerticalAlignment.CENTER);
|
||||
stWrap.setBorderTop(BorderStyle.MEDIUM);
|
||||
stWrap.setBorderLeft(BorderStyle.MEDIUM);
|
||||
stWrap.setBorderRight(BorderStyle.MEDIUM);
|
||||
stWrap.setBorderBottom(BorderStyle.MEDIUM);
|
||||
mergeText(s, 4, 5, 2, 2,
|
||||
"Очень длинный текст объединённой ячейки с переносом строк", stWrap);
|
||||
Cell b5 = s.getRow(4).createCell(3);
|
||||
b5.setCellValue(true);
|
||||
b5.setCellStyle(plain);
|
||||
CellStyle stTintFill = wb.createCellStyle();
|
||||
XSSFColor tintClr = new XSSFColor();
|
||||
CTColor tintCt = tintClr.getCTColor();
|
||||
tintCt.setTheme(THEME_ACCENT1);
|
||||
tintCt.setTint(TINT_60);
|
||||
stTintFill.setFillForegroundColor(tintClr);
|
||||
stTintFill.setFillPattern(FillPatternType.SOLID_FOREGROUND);
|
||||
stTintFill.setBorderBottom(BorderStyle.DASHED);
|
||||
cell(s, 4, 4, "tint-заливка", stTintFill);
|
||||
inlineStr(s, 4, 5, "инлайн-строка");
|
||||
cell(s, 5, 4, "справа", stRight);
|
||||
|
||||
// 2×2 merge F3:G4 с vAlign center и Calibri.
|
||||
CellStyle stBlock = wb.createCellStyle();
|
||||
Font calibri = wb.createFont();
|
||||
calibri.setFontName("Calibri");
|
||||
stBlock.setFont(calibri);
|
||||
stBlock.setVerticalAlignment(VerticalAlignment.CENTER);
|
||||
stBlock.setBorderBottom(BorderStyle.DASHED);
|
||||
mergeText(s, 2, 3, 5, 6, "Крупный блок", stBlock);
|
||||
|
||||
// Rich text: половина строки жирным (shared string с runs).
|
||||
Font boldHalf = wb.createFont();
|
||||
boldHalf.setBold(true);
|
||||
XSSFRichTextString rich = new XSSFRichTextString("обычный и ЖИРНЫЙ текст");
|
||||
rich.applyFont(10, 16, boldHalf);
|
||||
Cell richCell = rowOf(s, 6).createCell(0);
|
||||
richCell.setCellValue(rich);
|
||||
|
||||
// Скрытые строка 8 и столбец H (индекс 7).
|
||||
cell(s, 7, 0, "скрытая строка", plain);
|
||||
cell(s, 0, 7, "скрытый столбец", plain);
|
||||
rowOf(s, 7).setZeroHeight(true);
|
||||
s.setColumnHidden(7, true);
|
||||
|
||||
XSSFSheet notes = wb.createSheet("Заметки");
|
||||
CellStyle stItalic = wb.createCellStyle();
|
||||
Font italic = wb.createFont();
|
||||
italic.setItalic(true);
|
||||
italic.setFontName("Calibri");
|
||||
stItalic.setFont(italic);
|
||||
cell(notes, 0, 0, "Заметка", stItalic);
|
||||
cell(notes, 1, 0, -42.0, plain);
|
||||
|
||||
save(wb, out);
|
||||
}
|
||||
}
|
||||
|
||||
/** NumFmt: форматные кода v1 — целые/дроби, проценты, научный, деньги, даты, время, scale, General. */
|
||||
private static void numFmt(Path out) throws Exception {
|
||||
try (XSSFWorkbook wb = new XSSFWorkbook()) {
|
||||
XSSFSheet s = wb.createSheet("Formats");
|
||||
DataFormats f = new DataFormats(wb);
|
||||
|
||||
CellStyle label = wb.createCellStyle();
|
||||
Font bold = wb.createFont();
|
||||
bold.setBold(true);
|
||||
label.setFont(bold);
|
||||
cell(s, 0, 0, "numFmt", label);
|
||||
|
||||
fmt(s, 1, "general", "123456.789", f.general(), null);
|
||||
fmt(s, 2, "two-decimals", 3.14159, f.custom("0.00"), null);
|
||||
fmt(s, 3, "thousands", 1234.5, f.custom("#,##0"), null);
|
||||
fmt(s, 4, "money-pos", 1234.0, f.custom("$#,##0.00_);($#,##0.00)"), null);
|
||||
fmt(s, 5, "money-neg", -1234.5, f.custom("$#,##0.00_);($#,##0.00)"), null);
|
||||
fmt(s, 6, "percent", 0.425, f.custom("0.0%"), null);
|
||||
fmt(s, 7, "scientific", 12234567.0, f.custom("0.00E+00"), null);
|
||||
fmt(s, 8, "scale-millions", 12345678.0, f.custom("#,##0,,"), null);
|
||||
fmt(s, 9, "date-custom", 45629.0, f.custom("dd.mm.yyyy"), null);
|
||||
fmt(s, 10, "date-builtin14", 45629.0, (short) 14, null);
|
||||
fmt(s, 11, "weekday", 45629.0, f.custom("ddd"), null);
|
||||
fmt(s, 12, "long-datetime", 45629.7708333333, f.custom("dd mmmm yyyy hh:mm"), null);
|
||||
fmt(s, 13, "time-builtin20", 0.75, (short) 20, null);
|
||||
fmt(s, 14, "elapsed", 1.5, f.custom("[h]:mm"), null);
|
||||
fmt(s, 15, "red-section", -1.5, f.custom("[Red]0.00"), null);
|
||||
fmt(s, 16, "text-section", "привет", f.custom("0.00;-0.00;0.00;@"),
|
||||
"инлайн");
|
||||
fmt(s, 17, "builtin10", 3.14159, (short) 10, null);
|
||||
fmt(s, 18, "accounting", 1234.56,
|
||||
f.custom("_(* #,##0_);_(* (#,##0);_(* \"-\"??);_(@)"), null);
|
||||
fmt(s, 19, "str-numeric", "12.5", f.custom("0.00"), "инлайн");
|
||||
fmt(s, 20, "neg-zero", -0.0, f.custom("0.00"), null);
|
||||
fmt(s, 21, "serial-60", 60.0, f.custom("dd.mm.yyyy"), null);
|
||||
|
||||
save(wb, out);
|
||||
}
|
||||
}
|
||||
|
||||
/** Лист-1904: workbookPr date1904="1", serial 0/61 + пара дат. */
|
||||
private static void dates1904(Path out) throws Exception {
|
||||
try (XSSFWorkbook wb = new XSSFWorkbook()) {
|
||||
CTWorkbook ct = wb.getCTWorkbook();
|
||||
if (!ct.isSetWorkbookPr()) {
|
||||
ct.addNewWorkbookPr();
|
||||
}
|
||||
ct.getWorkbookPr().setDate1904(true);
|
||||
|
||||
XSSFSheet s = wb.createSheet("Dates1904");
|
||||
CellStyle st = wb.createCellStyle();
|
||||
st.setDataFormat(wb.createDataFormat().getFormat("dd.mm.yyyy hh:mm"));
|
||||
cell(s, 0, 0, "epoch", st);
|
||||
Cell c0 = s.getRow(0).createCell(1);
|
||||
c0.setCellValue(0);
|
||||
c0.setCellStyle(st);
|
||||
cell(s, 1, 0, "serial 61", st);
|
||||
Cell c61 = s.getRow(1).createCell(1);
|
||||
c61.setCellValue(61);
|
||||
c61.setCellStyle(st);
|
||||
cell(s, 2, 0, "date", st);
|
||||
Cell c = s.getRow(2).createCell(1);
|
||||
c.setCellValue(java.time.LocalDate.of(2024, 12, 3));
|
||||
c.setCellStyle(st);
|
||||
save(wb, out);
|
||||
}
|
||||
}
|
||||
|
||||
/** Широкий лист: 40 столбцов × 60 строк, ручной разрыв строки, merge через границу среза. */
|
||||
private static void wide(Path out) throws Exception {
|
||||
try (XSSFWorkbook wb = new XSSFWorkbook()) {
|
||||
XSSFSheet s = wb.createSheet("Wide");
|
||||
CellStyle plain = wb.createCellStyle();
|
||||
for (int c = 0; c < WIDE_COLS; c++) {
|
||||
s.setColumnWidth(c, COL_WIDTH_12);
|
||||
cell(s, 0, c, "Столбец " + (c + 1), plain);
|
||||
}
|
||||
for (int r = 1; r < WIDE_ROWS; r++) {
|
||||
for (int c = 0; c < WIDE_COLS; c++) {
|
||||
cell(s, r, c, "R" + (r + 1) + "C" + (c + 1), plain);
|
||||
}
|
||||
}
|
||||
// Merge через ожидаемую границу первого среза (11-й столбец).
|
||||
mergeText(s, 19, 19, 10, 12, "через границу среза", plain);
|
||||
s.setRowBreak(WIDE_ROW_BREAK);
|
||||
save(wb, out);
|
||||
}
|
||||
}
|
||||
|
||||
/** FitToPage: 20 столбцов, fitToPage+fitToWidth, landscape, A4, поля 0.5″. */
|
||||
private static void fitToPage(Path out) throws Exception {
|
||||
try (XSSFWorkbook wb = new XSSFWorkbook()) {
|
||||
XSSFSheet s = wb.createSheet("Fit");
|
||||
CellStyle plain = wb.createCellStyle();
|
||||
for (int c = 0; c < 20; c++) {
|
||||
s.setColumnWidth(c, COL_WIDTH_12);
|
||||
cell(s, 0, c, "К" + (c + 1), plain);
|
||||
}
|
||||
for (int r = 1; r < 10; r++) {
|
||||
for (int c = 0; c < 20; c++) {
|
||||
cell(s, r, c, "F" + (r + 1) + "-" + (c + 1), plain);
|
||||
}
|
||||
}
|
||||
s.setFitToPage(true);
|
||||
PrintSetup ps = s.getPrintSetup();
|
||||
ps.setFitWidth((short) 1);
|
||||
ps.setFitHeight((short) 0);
|
||||
ps.setLandscape(true);
|
||||
ps.setPaperSize(PrintSetup.A4_PAPERSIZE);
|
||||
s.setMargin(Sheet.LeftMargin, 0.5);
|
||||
s.setMargin(Sheet.RightMargin, 0.5);
|
||||
s.setMargin(Sheet.TopMargin, 0.5);
|
||||
s.setMargin(Sheet.BottomMargin, 0.5);
|
||||
save(wb, out);
|
||||
}
|
||||
}
|
||||
|
||||
/** Рисунки: bar- и line-диаграммы (кириллица) + PNG 100×60, все twoCellAnchor. */
|
||||
private static void chartImage(Path out) throws Exception {
|
||||
try (XSSFWorkbook wb = new XSSFWorkbook()) {
|
||||
XSSFSheet s = wb.createSheet("Графики");
|
||||
CellStyle plain = wb.createCellStyle();
|
||||
String[] cats = {"I кв.", "II кв.", "III кв.", "IV кв."};
|
||||
double[] sales = {120, 200, 150, 250};
|
||||
double[] services = {80, 120, 170, 140};
|
||||
int first = 29;
|
||||
for (int i = 0; i < cats.length; i++) {
|
||||
cell(s, first + i, 0, cats[i], plain);
|
||||
cell(s, first + i, 1, sales[i], plain);
|
||||
cell(s, first + i, 2, services[i], plain);
|
||||
}
|
||||
XSSFDrawing drawing = s.createDrawingPatriarch();
|
||||
|
||||
XSSFChart bar = drawing.createChart(
|
||||
new XSSFClientAnchor(0, 0, 0, 0, 5, 1, 11, 14));
|
||||
bar.setTitleText("Продажи по кварталам");
|
||||
XDDFCategoryAxis barCat = bar.createCategoryAxis(AxisPosition.BOTTOM);
|
||||
XDDFValueAxis barVal = bar.createValueAxis(AxisPosition.LEFT);
|
||||
barVal.setCrosses(AxisCrosses.AUTO_ZERO);
|
||||
XDDFChartData barData = bar.createData(ChartTypes.BAR, barCat, barVal);
|
||||
addSeries(barData, s, first, sales.length);
|
||||
bar.plot(barData);
|
||||
|
||||
XSSFChart line = drawing.createChart(
|
||||
new XSSFClientAnchor(0, 0, 0, 0, 5, 16, 11, 28));
|
||||
line.setTitleText("Динамика");
|
||||
XDDFCategoryAxis lineCat = line.createCategoryAxis(AxisPosition.BOTTOM);
|
||||
XDDFValueAxis lineVal = line.createValueAxis(AxisPosition.LEFT);
|
||||
lineVal.setCrosses(AxisCrosses.AUTO_ZERO);
|
||||
XDDFChartData lineData = line.createData(ChartTypes.LINE, lineCat, lineVal);
|
||||
addSeries(lineData, s, first, sales.length);
|
||||
line.plot(lineData);
|
||||
|
||||
byte[] png = makePng();
|
||||
int picIdx = wb.addPicture(png, Workbook.PICTURE_TYPE_PNG);
|
||||
drawing.createPicture(
|
||||
new XSSFClientAnchor(0, 0, 0, 0, 0, 17, 2, 20), picIdx);
|
||||
|
||||
save(wb, out);
|
||||
}
|
||||
}
|
||||
|
||||
/** Лимит страниц: 1 столбец, 130 ручных разрывов (оценка > MAX_PAGES). */
|
||||
private static void pageLimit(Path out) throws Exception {
|
||||
try (XSSFWorkbook wb = new XSSFWorkbook()) {
|
||||
XSSFSheet s = wb.createSheet("Long");
|
||||
CellStyle plain = wb.createCellStyle();
|
||||
for (int r = 0; r <= PAGE_LIMIT_BREAKS; r++) {
|
||||
cell(s, r, 0, "Строка " + (r + 1), plain);
|
||||
if (r < PAGE_LIMIT_BREAKS) {
|
||||
s.setRowBreak(r);
|
||||
}
|
||||
}
|
||||
save(wb, out);
|
||||
}
|
||||
}
|
||||
|
||||
// ================== Вспомогательные ==================
|
||||
|
||||
/** Категории A(first..) и две числовые серии B/C того же диапазона. */
|
||||
private static void addSeries(XDDFChartData data, XSSFSheet s, int first, int count) {
|
||||
XDDFCategoryDataSource categories = XDDFDataSourcesFactory.fromStringCellRange(
|
||||
s, new CellRangeAddress(first, first + count - 1, 0, 0));
|
||||
XDDFNumericalDataSource<Double> sales = XDDFDataSourcesFactory.fromNumericCellRange(
|
||||
s, new CellRangeAddress(first, first + count - 1, 1, 1));
|
||||
XDDFNumericalDataSource<Double> services = XDDFDataSourcesFactory.fromNumericCellRange(
|
||||
s, new CellRangeAddress(first, first + count - 1, 2, 2));
|
||||
XDDFChartData.Series s1 = data.addSeries(categories, sales);
|
||||
s1.setTitle("Продукты");
|
||||
XDDFChartData.Series s2 = data.addSeries(categories, services);
|
||||
s2.setTitle("Услуги");
|
||||
}
|
||||
|
||||
/** PNG 100×60: красный круг на белом — отличие от сплошных заливок. */
|
||||
private static byte[] makePng() throws Exception {
|
||||
BufferedImage img = new BufferedImage(100, 60, BufferedImage.TYPE_INT_RGB);
|
||||
Graphics2D g = img.createGraphics();
|
||||
g.setColor(Color.WHITE);
|
||||
g.fillRect(0, 0, 100, 60);
|
||||
g.setColor(new Color(220, 30, 30));
|
||||
g.fillOval(20, 5, 50, 50);
|
||||
g.setColor(new Color(20, 80, 200));
|
||||
g.fillRect(70, 40, 25, 15);
|
||||
g.dispose();
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
ImageIO.write(img, "png", bos);
|
||||
return bos.toByteArray();
|
||||
}
|
||||
|
||||
/** Ячейка с числом/строкой и стилем; строку создаёт при необходимости. */
|
||||
private static Cell cell(Sheet s, int row, int col, String text, CellStyle st) {
|
||||
Cell c = rowOf(s, row).createCell(col);
|
||||
c.setCellValue(text);
|
||||
c.setCellStyle(st);
|
||||
return c;
|
||||
}
|
||||
|
||||
/** Ячейка с числом и стилем. */
|
||||
private static Cell cell(Sheet s, int row, int col, double value, CellStyle st) {
|
||||
Cell c = rowOf(s, row).createCell(col);
|
||||
c.setCellValue(value);
|
||||
c.setCellStyle(st);
|
||||
return c;
|
||||
}
|
||||
|
||||
/** inlineStr: {@code c/@t="inlineStr"} + {@code is/t} (ECMA-376 §18.3.1.53). */
|
||||
private static void inlineStr(Sheet s, int row, int col, String text) {
|
||||
XSSFCell c = (XSSFCell) rowOf(s, row).createCell(col);
|
||||
CTCell ct = c.getCTCell();
|
||||
ct.setT(STCellType.INLINE_STR);
|
||||
ct.addNewIs().setT(text);
|
||||
}
|
||||
|
||||
/** merged region с текстом и стилем в origin-ячейке. */
|
||||
private static void mergeText(Sheet s, int row1, int row2, int col1, int col2,
|
||||
String text, CellStyle st) {
|
||||
cell(s, row1, col1, text, st);
|
||||
for (int r = row1; r <= row2; r++) {
|
||||
for (int c = col1 + (r == row1 ? 1 : 0); c <= col2; c++) {
|
||||
Cell empty = rowOf(s, r).createCell(c);
|
||||
empty.setCellStyle(st);
|
||||
}
|
||||
}
|
||||
s.addMergedRegion(new CellRangeAddress(row1, row2, col1, col2));
|
||||
}
|
||||
|
||||
/**
|
||||
* Ячейка форматной строки: A — метка, B — значение (inlineStr — когда
|
||||
* {@code inline} непустое), C — подтверждение типа значения.
|
||||
*/
|
||||
private static void fmt(Sheet s, int row, String name, Object value,
|
||||
short fmtId, String inline) {
|
||||
CellStyle st = s.getWorkbook().createCellStyle();
|
||||
st.setDataFormat(fmtId);
|
||||
cell(s, row, 0, name, st);
|
||||
Cell c = rowOf(s, row).createCell(1);
|
||||
if (value instanceof Double) {
|
||||
c.setCellValue((Double) value);
|
||||
} else if (inline == null) {
|
||||
c.setCellValue(String.valueOf(value));
|
||||
}
|
||||
if (inline != null) {
|
||||
CTCell ct = ((XSSFCell) c).getCTCell();
|
||||
ct.setT(STCellType.INLINE_STR);
|
||||
ct.addNewIs().setT(String.valueOf(value));
|
||||
}
|
||||
c.setCellStyle(st);
|
||||
}
|
||||
|
||||
private static Row rowOf(Sheet s, int row) {
|
||||
Row r = s.getRow(row);
|
||||
if (r == null) {
|
||||
r = s.createRow(row);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/** Таблица форматов с кэшем custom-id (один DataFormat на лист). */
|
||||
private static final class DataFormats {
|
||||
private final Workbook wb;
|
||||
|
||||
DataFormats(Workbook wb) {
|
||||
this.wb = wb;
|
||||
}
|
||||
|
||||
/** General — id 0 (встроенный). */
|
||||
short general() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** Custom-код: ≥164, дубликаты кода — один id. */
|
||||
short custom(String code) {
|
||||
return wb.createDataFormat().getFormat(code);
|
||||
}
|
||||
}
|
||||
|
||||
/** Проверка, что POI записал ожидаемый тип (защита генератора от тихих изменений). */
|
||||
private static void assertType(Cell c, CellType expected) {
|
||||
if (c.getCellType() != expected) {
|
||||
throw new IllegalStateException("Ожидался тип " + expected
|
||||
+ ", записан " + c.getCellType());
|
||||
}
|
||||
}
|
||||
|
||||
private static void save(XSSFWorkbook wb, Path out) throws Exception {
|
||||
// Контроль типа булевой ячейки базовой фикстуры до записи (после
|
||||
// записи POI-объект уже сброшен в save).
|
||||
Sheet base = wb.getSheet("Отчёт");
|
||||
if (base != null) {
|
||||
assertType(base.getRow(4).getCell(3), CellType.BOOLEAN);
|
||||
}
|
||||
try (FileOutputStream fos = new FileOutputStream(out.toFile())) {
|
||||
wb.write(fos);
|
||||
}
|
||||
System.out.println(" создан: " + out.getFileName()
|
||||
+ " (" + new File(out.toString()).length() + " байт)");
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Reference in New Issue
Block a user