Java POI HSSFWorkbook 解决 OLE2NotOfficeXmlFileException 异常,生成 Excel 折线图
该错误是由于使用了XSSFWorkbook来处理OLE2格式的Excel文件,而XSSFWorkbook只能处理OOXML格式的Excel文件。要解决这个问题,可以使用HSSFWorkbook来处理OLE2格式的Excel文件。修改代码如下:
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.hssf.usermodel.HSSFDrawing;
import org.apache.poi.hssf.usermodel.HSSFChart;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFLineChartData;
import org.apache.poi.hssf.usermodel.HSSFLineChartData.Series;
import org.apache.poi.hssf.usermodel.HSSFLineChart;
import org.apache.poi.hssf.usermodel.HSSFChartLegend;
import org.apache.poi.hssf.usermodel.HSSFChartAxis;
import org.apache.poi.hssf.usermodel.HSSFValueAxis;
import org.apache.poi.hssf.usermodel.HSSFCategoryAxis;
import org.apache.poi.hssf.usermodel.HSSFChartFactory;
import org.apache.poi.hssf.usermodel.HSSFChartTypes;
import org.apache.poi.hssf.usermodel.HSSFDataSources;
import org.apache.poi.hssf.usermodel.HSSFDataSources.ChartDataSource;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class ExcelChartExample01 {
public static void main(String[] args) {
try {
// 读取Excel文件
FileInputStream fileIn = new FileInputStream("巴新EDEVU水库数据处理表.xls");
Workbook workbook = new HSSFWorkbook(fileIn);
Sheet sheet = workbook.getSheet("P9");
// 创建折线图
Drawing drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 4, 1, 10, 20);
Chart chart = drawing.createChart(anchor);
ChartLegend legend = chart.getOrCreateLegend();
legend.setPosition(LegendPosition.BOTTOM);
// 创建数据系列
ChartAxis bottomAxis = chart.getChartAxisFactory().createCategoryAxis(AxisPosition.BOTTOM);
ValueAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT);
leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);
// 创建数据源
ChartDataSource<Number> xs = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(11, 85, 0, 0));
ChartDataSource<Number> ys = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(11, 85, 2, 2));
// 添加数据系列
LineChartData data = chart.getChartDataFactory().createLineChartData();
Series series = data.addSeries(xs, ys);
series.setTitle("数据折线图");
// 绘制图表
chart.plot(data);
// 保存Excel文件
FileOutputStream fileOut = new FileOutputStream("巴新EDEVU水库数据处理表.xls");
workbook.write(fileOut);
fileOut.close();
System.out.println("折线图已创建并保存到Excel文件中。");
} catch (IOException e) {
e.printStackTrace();
}
}
}
请注意,修改后的代码使用了HSSFWorkbook来处理Excel文件,同时使用了HSSF开头的类和方法。另外,Excel文件的扩展名也需要修改为.xls。
原文地址: https://www.cveoy.top/t/topic/f3Ru 著作权归作者所有。请勿转载和采集!