JAVA poi生成折线图(数据有负数比较麻烦,暂时代码还没解决,打开文档的图表工具设置成“样式1”可解决)
导入依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
一、不使用模板,直接生成word图表(可能会导致wps和office打开的格式不一样,甚至打不开,跟数据有一点的关系)
@Test
void test1() throws Exception {
XWPFDocument document = new XWPFDocument();
int charNum = 3;
for (int num = 0; num < charNum; num++) {
setDocumentTitle(document, DocumentTitleEnum.H1.getCode(), "一级标题");
setDocumentTitle(document, DocumentTitleEnum.H2.getCode(), "二级标题");
setDocumentTitle(document, DocumentTitleEnum.H3.getCode(), "三级标题");
setDocumentTitle(document, DocumentTitleEnum.P.getCode(), "正文标题");
XWPFChart chart = document.createChart(15 * Units.EMU_PER_CENTIMETER, 10 * Units.EMU_PER_CENTIMETER);
chart.setTitleText("多维度折线图" + (num + 1));
chart.setTitleOverlay(false);
XDDFChartLegend legend = chart.getOrAddLegend();
legend.setPosition(LegendPosition.TOP);
XDDFCategoryAxis xAxis = chart.createCategoryAxis(AxisPosition.BOTTOM);
xAxis.setTitle("日期(年月)");
String[] xAxisData = new String[]{
"2021-01", "2021-02", "2021-03", "2021-04", "2021-05", "2021-06",
"2021-07", "2021-08", "2021-09", "2021-10", "2021-11", "2021-12"
};
XDDFCategoryDataSource xAxisSource = XDDFDataSourcesFactory.fromArray(xAxisData);
XDDFValueAxis yAxis = chart.createValueAxis(AxisPosition.LEFT);
yAxis.setTitle("粉丝数(个)");
XDDFLineChartData lineChart = (XDDFLineChartData) chart.createData(ChartTypes.LINE, xAxis, yAxis);
Integer[][] yAxisData = new Integer[][]{
{10, 35, -21, 46, 79, 88, 39, 102, 71, null, 99, 57},
{20, 25, 31, 56, null, null, 49, 92, 61, -18, 79, 67}
};
for (int i = 0; i < yAxisData.length; i++) {
Integer[] data = yAxisData[i];
XDDFNumericalDataSource<Integer> yAxisSource = XDDFDataSourcesFactory.fromArray(data);
XDDFLineChartData.Series lineSeries1 = (XDDFLineChartData.Series) lineChart.addSeries(xAxisSource, yAxisSource);
lineSeries1.setTitle("折线" + (i + 1), null);
lineSeries1.setSmooth(true);
lineSeries1.setMarkerStyle(MarkerStyle.NONE);
}
CTDispBlanksAs disp = CTDispBlanksAs.Factory.newInstance();
disp.setVal(STDispBlanksAs.GAP);
chart.getCTChart().setDispBlanksAs(disp);
chart.plot(lineChart);
}
String date = DateUtil.now().replace("-","").replace(":", "").replace(" ", "");
FileOutputStream fos = new FileOutputStream("C:\\Users\\admin\\Desktop\\LineChart" + date + ".docx");
document.write(fos);
fos.close();
document.close();
}
二、使用模板导出(模板里面有多少个图表,就只能导出多少个图标,不够灵活,好处是兼容wps和office)
public static void main(String[] args) throws Exception {
final String returnurl = "C:\\Users\\admin\\Desktop\\新建文件夹\\barchartresult.docx";
final String templateurl = "E:\\poi-demo-master\\poi-demo\\src\\main\\resources\\barchart.docx";
InputStream is = new FileInputStream(new File(templateurl1));
XWPFDocument doc = new XWPFDocument(is);
doCharts(doc);
try {
FileOutputStream fos = new FileOutputStream(templateurl1);
doc.write(fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void doCharts(XWPFDocument doc) throws Exception {
List<String> keys = new ArrayList<>();
Map<String, POIXMLDocumentPart> chartsMap = new HashMap<String, POIXMLDocumentPart>();
List<POIXMLDocumentPart> relations = doc.getRelations();
for (POIXMLDocumentPart poixmlDocumentPart : relations) {
if (poixmlDocumentPart instanceof XWPFChart) {
String str = poixmlDocumentPart.toString();
String key = str.replaceAll("Name: ", "")
.replaceAll(" - Content Type: application/vnd\\.openxmlformats-officedocument\\.drawingml\\.chart\\+xml", "").trim();
chartsMap.put(key, poixmlDocumentPart);
keys.add(key);
}
}
Collections.sort(keys);
for (int i = 0; i < 3; i++) {
doCharts(chartsMap.get(keys.get(i)));
}
}
public static void doCharts(POIXMLDocumentPart poixmlDocumentPart) {
List<String> titleArr = new ArrayList<String>();
titleArr.add("");
titleArr.add("折线1");
titleArr.add("折线2");
titleArr.add("折线3");
List<String> fldNameArr = new ArrayList<String>();
fldNameArr.add("item1");
fldNameArr.add("item2");
fldNameArr.add("item3");
fldNameArr.add("item4");
List<Map<String, String>> listItemsByType = new ArrayList<Map<String, String>>();
for (int i = 0; i < 9; i++) {
Map<String, String> base1 = new HashMap<String, String>();
String[] array = {null, "1", "2", "3", "4", "5", "-6", "7", "8", "-9"};
base1.put("item1", "2020-0"+(i+1));
base1.put("item2", array[(int)(Math.random() * array.length)]);
base1.put("item3", array[(int)(Math.random() * array.length)]);
base1.put("item4", array[(int)(Math.random() * array.length)]);
listItemsByType.add(base1);
}
new PoiWordTools().replaceLineCharts(poixmlDocumentPart, titleArr, fldNameArr, listItemsByType);
}
三、使用直接导出+模板(结合了两者的好处,导出的格式还会有一点问题,不过问题不大)
@Test
void test3() throws Exception {
XWPFDocument document = new XWPFDocument();
setDocumentTitle(document, DocumentTitleEnum.H1.getCode(), "一级标题");
setDocumentTitle(document, DocumentTitleEnum.H2.getCode(), "二级标题");
setDocumentTitle(document, DocumentTitleEnum.H3.getCode(), "三级标题");
setDocumentTitle(document, DocumentTitleEnum.P.getCode(), "正文标题");
for (int num = 0; num < chartList.size(); num++) {
ChartData chartData = chartList.get(num);
XWPFChart chart = document.createChart(15 * Units.EMU_PER_CENTIMETER, 10 * Units.EMU_PER_CENTIMETER);
chart.setTitleText(chartData.getChartTitle());
chart.setTitleOverlay(false);
XDDFChartLegend legend = chart.getOrAddLegend();
legend.setPosition(LegendPosition.TOP);
XDDFCategoryAxis xAxis = chart.createCategoryAxis(AxisPosition.BOTTOM);
xAxis.setPosition(AxisPosition.BOTTOM);
xAxis.setTickLabelPosition(AxisTickLabelPosition.LOW);
xAxis.setMajorTickMark(AxisTickMark.NONE);
String[] xAxisData = new String[]{};
XDDFCategoryDataSource xAxisSource = XDDFDataSourcesFactory.fromArray(xAxisData);
XDDFValueAxis yAxis = chart.createValueAxis(AxisPosition.LEFT);
yAxis.setTitle(chartData.getYTitle());
yAxis.setMajorTickMark(AxisTickMark.OUT);
yAxis.setCrosses(AxisCrosses.AUTO_ZERO);
yAxis.setCrossBetween(AxisCrossBetween.BETWEEN);
XDDFLineChartData lineChart = (XDDFLineChartData) chart.createData(ChartTypes.LINE, xAxis, yAxis);
lineChart.setVaryColors(true);
chart.plot(lineChart);
}
String templateUrl = "src/data/wordLineChartTemp.docx";
FileOutputStream fos = new FileOutputStream(templateUrl);
document.write(fos);
fos.close();
document.close();
String date = DateUtil.now().replace("-","").replace(":", "").replace(" ", "");
String resultUrl = "C:\\Users\\admin\\Desktop\\LineChart" + date + ".docx";
updateTempFile(templateUrl, resultUrl);
}
private void updateTempFile(String templateUrl, String resultUrl) throws Exception{
File file = new File(templateUrl);
InputStream is = new FileInputStream(new File(templateUrl));
XWPFDocument doc = new XWPFDocument(is);
repalceTempFile(doc);
try {
FileOutputStream fos = new FileOutputStream(resultUrl);
doc.write(fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
is.close();
file.delete();
}
}
private void repalceTempFile(XWPFDocument doc) throws Exception {
List<String> keys = new ArrayList<>();
Map<String, POIXMLDocumentPart> chartsMap = new HashMap<String, POIXMLDocumentPart>();
List<POIXMLDocumentPart> relations = doc.getRelations();
for (POIXMLDocumentPart poixmlDocumentPart : relations) {
if (poixmlDocumentPart instanceof XWPFChart) {
String str = poixmlDocumentPart.toString();
String key = str.replaceAll("Name: ", "")
.replaceAll(" - Content Type: application/vnd\\.openxmlformats-officedocument\\.drawingml\\.chart\\+xml", "").trim();
chartsMap.put(key, poixmlDocumentPart);
keys.add(key);
}
}
Collections.sort(keys);
for (int i = 0; i < keys.size(); i++) {
doChart(chartsMap.get(keys.get(i)));
}
}
private void doChart(POIXMLDocumentPart poixmlDocumentPart) {
List<String> titleArr = new ArrayList<String>();
titleArr.add("");
titleArr.add("折线1");
titleArr.add("折线2");
titleArr.add("折线3");
List<String> fldNameArr = new ArrayList<String>();
fldNameArr.add("item1");
fldNameArr.add("item2");
fldNameArr.add("item3");
fldNameArr.add("item4");
List<Map<String, String>> listItemsByType = new ArrayList<Map<String, String>>();
for (int i = 0; i < 9; i++) {
Map<String, String> base1 = new HashMap<String, String>();
String[] array = {"0", null, "2", "3", "4", "5", "-6", "7", "8", "-9"};
base1.put("item1", "2020-0"+(i+1));
base1.put("item2", array[(int)(Math.random() * array.length)]);
base1.put("item3", array[(int)(Math.random() * array.length)]);
base1.put("item4", array[(int)(Math.random() * array.length)]);
listItemsByType.add(base1);
}
new PoiWordTools().replaceLineCharts(poixmlDocumentPart, titleArr, fldNameArr, listItemsByType);
}
四、需要的类
4、1 PoiWordTitle
public class PoiWordTitle {
public void setBarTitle(CTChart ctChart, String title) {
CTTitle ctTitle = ctChart.getTitle();
CTTx ctTx = ctTitle.getTx();
if (null != ctTx) {
CTTextBody ctTextBody = ctTx.getRich();
List<CTTextParagraph> ctTextParagraphslist = ctTextBody.getPList();
CTTextParagraph ctTextParagraph1 = ctTextParagraphslist.get(0);
List<CTRegularTextRun> ctRegularTextRunslist = ctTextParagraph1.getRList();
ctRegularTextRunslist.get(0).setT(title);
}
}
}
4、2 PoiWordTools
public class PoiWordTools {
private static final BigDecimal bd2 = new BigDecimal("2");
public static void replaceRadarCharts(POIXMLDocumentPart poixmlDocumentPart,
List<String> titleArr, List<String> fldNameArr, List<Map<String, String>> listItemsByType) {
XWPFChart chart = (XWPFChart) poixmlDocumentPart;
chart.getCTChart();
CTChart ctChart = chart.getCTChart();
CTPlotArea plotArea = ctChart.getPlotArea();
CTRadarChart radarChart = plotArea.getRadarChartArray(0);
List<CTRadarSer> radarList = radarChart.getSerList();
new PoiWordTools().refreshExcel(chart, listItemsByType, fldNameArr, titleArr);
refreshRadarStrGraphContent(radarChart, radarList, listItemsByType, fldNameArr, 1);
}
public static void replaceBarCharts(POIXMLDocumentPart poixmlDocumentPart,
List<String> titleArr, List<String> fldNameArr, List<Map<String, String>> listItemsByType) {
XWPFChart chart = (XWPFChart) poixmlDocumentPart;
chart.getCTChart();
CTChart ctChart = chart.getCTChart();
CTPlotArea plotArea = ctChart.getPlotArea();
new PoiWordTitle().setBarTitle(ctChart, "我是修改后的标题");
CTBarChart barChart = plotArea.getBarChartArray(0);
List<CTBarSer> BarSerList = barChart.getSerList();
new PoiWordTools().refreshExcel(chart, listItemsByType, fldNameArr, titleArr);
refreshBarStrGraphContent(barChart, BarSerList, listItemsByType, fldNameArr, 1);
}
public static void replaceLineCharts(POIXMLDocumentPart poixmlDocumentPart,
List<String> titleArr, List<String> fldNameArr, List<Map<String, String>> listItemsByType) {
XWPFChart chart = (XWPFChart) poixmlDocumentPart;
chart.getCTChart();
CTDispBlanksAs disp = CTDispBlanksAs.Factory.newInstance();
disp.setVal(STDispBlanksAs.GAP);
chart.getCTChart().setDispBlanksAs(disp);
CTChart ctChart = chart.getCTChart();
CTPlotArea plotArea = ctChart.getPlotArea();
CTLineChart lineChart = plotArea.getLineChartArray(0);
List<CTLineSer> lineSerList = lineChart.getSerList();
new PoiWordTools().refreshExcel(chart, listItemsByType, fldNameArr, titleArr);
new PoiWordTools().refreshLineStrGraphContent(titleArr, lineChart, lineSerList, listItemsByType, fldNameArr, 1);
}
public static void replacePieCharts(POIXMLDocumentPart poixmlDocumentPart,
List<String> titleArr, List<String> fldNameArr, List<Map<String, String>> listItemsByType) {
XWPFChart chart = (XWPFChart) poixmlDocumentPart;
chart.getCTChart();
CTChart ctChart = chart.getCTChart();
CTPlotArea plotArea = ctChart.getPlotArea();
CTPieChart pieChart = plotArea.getPieChartArray(0);
List<CTPieSer> pieSerList = pieChart.getSerList();
new PoiWordTools().refreshExcel(chart, listItemsByType, fldNameArr, titleArr);
new PoiWordTools().refreshPieStrGraphContent(pieChart, pieSerList, listItemsByType, fldNameArr, 1);
}
public static void replaceCombinationCharts(POIXMLDocumentPart poixmlDocumentPart,
List<String> titleArr, List<String> fldNameArr, List<Map<String, String>> listItemsByType) {
XWPFChart chart = (XWPFChart) poixmlDocumentPart;
chart.getCTChart();
CTChart ctChart = chart.getCTChart();
CTPlotArea plotArea = ctChart.getPlotArea();
CTBarChart barChart = plotArea.getBarChartArray(0);
List<CTBarSer> barSerList = barChart.getSerList();
new PoiWordTools().refreshExcel(chart, listItemsByType, fldNameArr, titleArr);
refreshBarStrGraphContent(barChart, barSerList, listItemsByType, fldNameArr, 1);
CTLineChart lineChart = plotArea.getLineChartArray(0);
List<CTLineSer> lineSerList = lineChart.getSerList();
new PoiWordTools().refreshLineStrGraphContent(titleArr, lineChart, lineSerList, listItemsByType, fldNameArr, 3);
}
public static boolean refreshLineStrGraphContent(List<String> titleArr, Object typeChart,
List<?> serList, List<Map<String, String>> dataList, List<String> fldNameArr, int position) {
boolean result = true;
for (int i = 0; i < titleArr.size() - 1; i++) {
CTAxDataSource cat = null;
CTNumDataSource val = null;
CTLineSer ser = null;
try {
ser = ((CTLineChart) typeChart).getSerArray(i);
} catch (Exception e) {
ser = ((CTLineChart) typeChart).addNewSer();
}
CTSerTx tx = ser.getTx();
if (tx == null){
CTStrData ctStrData = ser.addNewTx().addNewStrRef().addNewStrCache();
ctStrData.addNewPt();
ctStrData.addNewPtCount().setVal(1L);
ser.addNewCat().addNewStrRef().addNewStrCache().addNewPtCount();
ser.addNewVal().addNewNumRef().addNewNumCache().addNewPtCount();
ser.addNewIdx().setVal(i);
ser.addNewOrder().setVal(i);
ser.addNewSpPr().addNewLn().setW(28575);
ser.addNewMarker().addNewSymbol().setVal(STMarkerStyle.NONE);
ser.addNewSmooth().setVal(true);
ser.addNewExtLst();
tx = ser.getTx();
}
tx.getStrRef().getStrCache().getPtList().get(0).setV(titleArr.get(i + 1));
tx.getStrRef().getStrCache().getPtList().get(0).setIdx(0L);
String StrRefF = "Sheet1!$" + getExcelCol(i + 2) + "$1";
tx.getStrRef().setF(StrRefF);
ser.getSmooth().setVal(true);
cat = ser.getCat();
val = ser.getVal();
CTStrData strData = cat.getStrRef().getStrCache();
CTNumData numData = val.getNumRef().getNumCache();
strData.setPtArray((CTStrVal[]) null);
numData.setPtArray((CTNumVal[]) null);
long idx = 0;
for (int j = 0; j < dataList.size(); j++) {
String value = "0";
String s = dataList.get(j).get(fldNameArr.get(i + position));
if (!"".equals(s) && s != null){
if (new BigDecimal(dataList.get(j).get(fldNameArr.get(i + position))) != null) {
value = new BigDecimal(dataList.get(j).get(fldNameArr.get(i + position))).toString();
}
} else {
value = null;
}
CTNumVal numVal = numData.addNewPt();
numVal.setIdx(idx);
numVal.setV(value);
CTStrVal sVal = strData.addNewPt();
sVal.setIdx(idx);
sVal.setV(dataList.get(j).get(fldNameArr.get(0)));
idx++;
}
numData.getPtCount().setVal(idx);
strData.getPtCount().setVal(idx);
String axisDataRange = new CellRangeAddress(1, dataList.size(), 0, 0)
.formatAsString("Sheet1", false);
cat.getStrRef().setF(axisDataRange);
String numDataRange = new CellRangeAddress(1, dataList.size(), i + position, i + position)
.formatAsString("Sheet1", false);
val.getNumRef().setF(numDataRange);
}
return result;
}
public static boolean refreshBarStrGraphContent(Object typeChart,
List<?> serList, List<Map<String, String>> dataList, List<String> fldNameArr, int position) {
boolean result = true;
for (int i = 0; i < serList.size(); i++) {
CTAxDataSource cat = null;
CTNumDataSource val = null;
CTBarSer ser = ((CTBarChart) typeChart).getSerArray(i);
CTSerTx tx = ser.getTx();
cat = ser.getCat();
val = ser.getVal();
CTStrData strData = cat.getStrRef().getStrCache();
CTNumData numData = val.getNumRef().getNumCache();
strData.setPtArray((CTStrVal[]) null);
numData.setPtArray((CTNumVal[]) null);
long idx = 0;
for (int j = 0; j < dataList.size(); j++) {
String value = "0";
if (new BigDecimal(dataList.get(j).get(fldNameArr.get(i + position))) != null) {
value = new BigDecimal(dataList.get(j).get(fldNameArr.get(i + position))).toString();
}
if (!"0".equals(value)) {
CTNumVal numVal = numData.addNewPt();
numVal.setIdx(idx);
numVal.setV(value);
}
CTStrVal sVal = strData.addNewPt();
sVal.setIdx(idx);
sVal.setV(dataList.get(j).get(fldNameArr.get(0)));
idx++;
}
numData.getPtCount().setVal(idx);
strData.getPtCount().setVal(idx);
String axisDataRange = new CellRangeAddress(1, dataList.size(), 0, 0)
.formatAsString("Sheet1", true);
cat.getStrRef().setF(axisDataRange);
String numDataRange = new CellRangeAddress(1, dataList.size(), i + position, i + position)
.formatAsString("Sheet1", true);
val.getNumRef().setF(numDataRange);
}
return result;
}
public static boolean refreshPieStrGraphContent(Object typeChart,
List<?> serList, List<Map<String, String>> dataList, List<String> fldNameArr, int position) {
boolean result = true;
for (int i = 0; i < serList.size(); i++) {
CTAxDataSource cat = null;
CTNumDataSource val = null;
CTPieSer ser = ((CTPieChart) typeChart).getSerArray(i);
cat = ser.getCat();
val = ser.getVal();
CTStrData strData = cat.getStrRef().getStrCache();
CTNumData numData = val.getNumRef().getNumCache();
strData.setPtArray((CTStrVal[]) null);
numData.setPtArray((CTNumVal[]) null);
long idx = 0;
for (int j = 0; j < dataList.size(); j++) {
String value = "0";
if (new BigDecimal(dataList.get(j).get(fldNameArr.get(i + position))) != null) {
value = new BigDecimal(dataList.get(j).get(fldNameArr.get(i + position))).toString();
}
if (!"0".equals(value)) {
CTNumVal numVal = numData.addNewPt();
numVal.setIdx(idx);
numVal.setV(value);
}
CTStrVal sVal = strData.addNewPt();
sVal.setIdx(idx);
sVal.setV(dataList.get(j).get(fldNameArr.get(0)));
idx++;
}
numData.getPtCount().setVal(idx);
strData.getPtCount().setVal(idx);
String axisDataRange = new CellRangeAddress(1, dataList.size(), 0, 0)
.formatAsString("Sheet1", true);
cat.getStrRef().setF(axisDataRange);
String numDataRange = new CellRangeAddress(1, dataList.size(), i + position, i + position)
.formatAsString("Sheet1", true);
val.getNumRef().setF(numDataRange);
}
return result;
}
public static boolean refreshExcel(XWPFChart chart,
List<Map<String, String>> dataList, List<String> fldNameArr, List<String> titleArr) {
boolean result = true;
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("Sheet1");
for (int i = 0; i < titleArr.size(); i++) {
if (sheet.getRow(0) == null) {
sheet.createRow(0).createCell(i).setCellValue(titleArr.get(i) == null ? "" : titleArr.get(i));
} else {
sheet.getRow(0).createCell(i).setCellValue(titleArr.get(i) == null ? "" : titleArr.get(i));
}
}
for (int i = 0; i < dataList.size(); i++) {
Map<String, String> baseFormMap = dataList.get(i);
for (int j = 0; j < fldNameArr.size(); j++) {
if (sheet.getRow(i + 1) == null) {
if (j == 0) {
try {
sheet.createRow(i + 1).createCell(j).setCellValue(baseFormMap.get(fldNameArr.get(j)) == null ? "" : baseFormMap.get(fldNameArr.get(j)));
} catch (Exception e) {
if (baseFormMap.get(fldNameArr.get(j)) == null) {
sheet.createRow(i + 1).createCell(j).setCellValue("");
} else {
sheet.createRow(i + 1).createCell(j).setCellValue(baseFormMap.get(fldNameArr.get(j)));
}
}
}
} else {
BigDecimal b = null;
String s = baseFormMap.get(fldNameArr.get(j));
if (!"".equals(s) && s != null){
b = new BigDecimal(baseFormMap.get(fldNameArr.get(j)));
} else {
System.out.println();
}
double value = 0d;
if (b != null) {
value = b.doubleValue();
}
if (value == 0) {
sheet.getRow(i + 1).createCell(j);
} else {
sheet.getRow(i + 1).createCell(j).setCellValue(b.doubleValue());
}
}
}
}
POIXMLDocumentPart xlsPart = chart.getRelations().get(0);
OutputStream xlsOut = xlsPart.getPackagePart().getOutputStream();
try {
wb.write(xlsOut);
xlsOut.close();
} catch (IOException e) {
e.printStackTrace();
result = false;
} finally {
if (wb != null) {
try {
wb.close();
} catch (IOException e) {
e.printStackTrace();
result = false;
}
}
}
return result;
}
public static void setWordCellSelfStyle(XWPFTableCell cell, String fontName, String fontSize, int fontBlod,
String alignment, String vertical, String fontColor,
String bgColor, String cellWidth, String content) {
BigInteger bFontSize = new BigInteger("24");
if (fontSize != null && !fontSize.equals("")) {
BigDecimal fontSizeBD = new BigDecimal(fontSize);
fontSizeBD = bd2.multiply(fontSizeBD);
fontSizeBD = fontSizeBD.setScale(0, BigDecimal.ROUND_HALF_UP);
bFontSize = new BigInteger(fontSizeBD.toString());
}
cell.setWidth(cellWidth);
CTTc tc = cell.getCTTc();
CTTcPr tcPr = tc.getTcPr();
if (tcPr == null) {
tcPr = tc.addNewTcPr();
}
CTVerticalJc vjc = tcPr.getVAlign();
if (vjc == null) {
vjc = tcPr.addNewVAlign();
}
vjc.setVal(vertical.equals("top") ? STVerticalJc.TOP : vertical.equals("bottom") ? STVerticalJc.BOTTOM : STVerticalJc.CENTER);
CTShd shd = tcPr.getShd();
if (shd == null) {
shd = tcPr.addNewShd();
}
shd.setFill(bgColor.substring(1));
CTP p = tc.getPList().get(0);
CTPPr ppr = p.getPPr();
if (ppr == null) {
ppr = p.addNewPPr();
}
CTJc jc = ppr.getJc();
if (jc == null) {
jc = ppr.addNewJc();
}
jc.setVal(alignment.equals("left") ? STJc.LEFT : alignment.equals("right") ? STJc.RIGHT : STJc.CENTER);
CTParaRPr pRpr = ppr.getRPr();
if (pRpr == null) {
pRpr = ppr.addNewRPr();
}
CTFonts pfont = pRpr.getRFonts();
if (pfont == null) {
pfont = pRpr.addNewRFonts();
}
pfont.setAscii(fontName);
pfont.setEastAsia(fontName);
pfont.setHAnsi(fontName);
CTOnOff pb = pRpr.getB();
if (pb == null) {
pb = pRpr.addNewB();
}
pb.setVal(fontBlod == 1 ? STOnOff.ON : STOnOff.OFF);
CTHpsMeasure psz = pRpr.getSz();
if (psz == null) {
psz = pRpr.addNewSz();
}
psz.setVal(bFontSize);
CTHpsMeasure pszCs = pRpr.getSzCs();
if (pszCs == null) {
pszCs = pRpr.addNewSzCs();
}
pszCs.setVal(bFontSize);
List<CTR> rlist = p.getRList();
CTR r = null;
if (rlist != null && rlist.size() > 0) {
r = rlist.get(0);
} else {
r = p.addNewR();
}
CTRPr rpr = r.getRPr();
if (rpr == null) {
rpr = r.addNewRPr();
}
CTFonts font = rpr.getRFonts();
if (font == null) {
font = rpr.addNewRFonts();
}
font.setAscii(fontName);
font.setEastAsia(fontName);
font.setHAnsi(fontName);
CTOnOff b = rpr.getB();
if (b == null) {
b = rpr.addNewB();
}
b.setVal(fontBlod == 1 ? STOnOff.ON : STOnOff.OFF);
CTColor color = rpr.getColor();
if (color == null) {
color = rpr.addNewColor();
}
if (content.contains("↓")) {
color.setVal("43CD80");
} else if (content.contains("↑")) {
color.setVal("943634");
} else {
color.setVal(fontColor.substring(1));
}
CTHpsMeasure sz = rpr.getSz();
if (sz == null) {
sz = rpr.addNewSz();
}
sz.setVal(bFontSize);
CTHpsMeasure szCs = rpr.getSzCs();
if (szCs == null) {
szCs = rpr.addNewSz();
}
szCs.setVal(bFontSize);
List<CTText> tlist = r.getTList();
CTText t = null;
if (tlist != null && tlist.size() > 0) {
t = tlist.get(0);
} else {
t = r.addNewT();
}
t.setStringValue(content);
}
public static String getZeroData(POIXMLDocumentPart poixmlDocumentPart) {
String text = "";
try {
XWPFChart chart = (XWPFChart) poixmlDocumentPart;
chart.getCTChart();
POIXMLDocumentPart xlsPart = chart.getRelations().get(0);
InputStream xlsin = xlsPart.getPackagePart().getInputStream();
Workbook workbook = new XSSFWorkbook(xlsin);
Sheet sheet = workbook.getSheetAt(0);
Row row = sheet.getRow(0);
Cell cell = row.getCell(0);
cell.setCellType(CellType.STRING);
text = cell.getStringCellValue();
System.out.println("(0,0)格子值:" + text);
xlsin.close();
} catch (Exception e) {
e.printStackTrace();
}
return text;
}
public static boolean refreshRadarStrGraphContent(Object typeChart,
List<?> serList, List<Map<String, String>> dataList, List<String> fldNameArr, int position) {
boolean result = true;
for (int i = 0; i < serList.size(); i++) {
CTAxDataSource cat = null;
CTNumDataSource val = null;
CTRadarSer ser = ((CTRadarChart) typeChart).getSerArray(i);
CTSerTx tx = ser.getTx();
cat = ser.getCat();
val = ser.getVal();
if (null != cat.getNumRef()) {
cat.unsetNumRef();
}
if (null != cat.getStrRef()) {
cat.unsetStrRef();
}
cat.addNewStrRef().addNewStrCache();
CTStrData strData = cat.getStrRef().getStrCache();
CTNumData numData = val.getNumRef().getNumCache();
strData.setPtArray((CTStrVal[]) null);
numData.setPtArray((CTNumVal[]) null);
long idx = 0;
for (int j = 0; j < dataList.size(); j++) {
String value = "0";
if (new BigDecimal(dataList.get(j).get(fldNameArr.get(i + position))) != null) {
value = new BigDecimal(dataList.get(j).get(fldNameArr.get(i + position))).toString();
}
if (!"0".equals(value)) {
CTNumVal numVal = numData.addNewPt();
numVal.setIdx(idx);
numVal.setV(value);
}
CTStrVal sVal = strData.addNewPt();
sVal.setIdx(idx);
sVal.setV(dataList.get(j).get(fldNameArr.get(0)));
idx++;
}
strData.addNewPtCount().setVal(idx);
numData.getPtCount().setVal(idx);
String axisDataRange = new CellRangeAddress(1, dataList.size(), 0, 0)
.formatAsString("Sheet1", true);
cat.getStrRef().setF(axisDataRange);
String numDataRange = new CellRangeAddress(1, dataList.size(), i + position, i + position)
.formatAsString("Sheet1", true);
val.getNumRef().setF(numDataRange);
}
return result;
}
private static String getExcelCol(int columnNumber) {
StringBuilder columnName = new StringBuilder();
while (columnNumber > 0) {
int remainder = (columnNumber - 1) % 26;
columnName.insert(0, (char) (remainder + 'A'));
columnNumber = (columnNumber - 1) / 26;
}
return columnName.toString();
}
}
4、3 DocumentTitleEnum
@Getter
public enum DocumentTitleEnum {
H1("2", "h1格式"),
H2("3", "h2格式"),
H3("4", "h3格式"),
P("5", "正文格式");
private final String code;
private final String message;
DocumentTitleEnum(String code, String message) {
this.code = code;
this.message = message;
}
}