欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 维修 > excel的导入和下载(poi)

excel的导入和下载(poi)

2025/3/13 23:54:10 来源:https://blog.csdn.net/2301_78703470/article/details/146185971  浏览:    关键词:excel的导入和下载(poi)
  • Apache POI官网https://poi.apache.org/

  • GitHub示例代码https://github.com/apache/poi

通过使用相关的Java库,如Apache POI、EasyPoi或EasyExcel,可以轻松地实现Excel文件的读写操作。

1.2 典型应用场景

  • 报表自动化生成(如导出统计表格)

  • 批量数据导入(如从Excel读取用户信息)

  • 文档模板填充(合同、通知等)

  • 服务器端文档格式转换

  • HSSF/XSSF:处理Excel(97-2003/2007+格式)

  • HWPF/XWPF:处理Word文档

  • HSLF/XSLF:处理PowerPoint

Maven依赖配置 

<!-- POI核心库 -->
<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>5.2.3</version>
</dependency>
<!-- 处理xlsx格式 -->
<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>5.2.3</version>
</dependency>

 创建第一个Excel文件

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;public class ExcelDemo {public static void main(String[] args) throws Exception {Workbook workbook = new XSSFWorkbook(); // 创建xlsx工作簿Sheet sheet = workbook.createSheet("用户列表");// 创建标题行Row headerRow = sheet.createRow(0);headerRow.createCell(0).setCellValue("ID");headerRow.createCell(1).setCellValue("姓名");// 添加数据Row dataRow = sheet.createRow(1);dataRow.createCell(0).setCellValue(1);dataRow.createCell(1).setCellValue("张三");// 保存文件try (FileOutputStream fos = new FileOutputStream("demo.xlsx")) {workbook.write(fos);}workbook.close();}
}

 读取数据

    public static void read() throws Exception {// 读取磁盘上面已经存在的Excel文件XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream("盘符名:\\***\\123.xlsx"));// 读取Excel文件里面的第一个sheet页XSSFSheet sheet = excel.getSheetAt(0);// 获取最后一行有数据的文件int lastRowNum = sheet.getLastRowNum();for (int i = 0; i <= lastRowNum; i++) {// 获取某一行XSSFRow row = sheet.getRow(i);String cellValue1 = row.getCell(0).getStringCellValue();String cellValue2 = row.getCell(1).getStringCellValue();String cellValue3 = row.getCell(2).getStringCellValue();System.out.println(cellValue1 + "\t" + cellValue2 + "\t" + cellValue3);}// 关闭资源excel.close();}

三、Excel高级操作技巧 

// 创建单元格样式
CellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);Font font = workbook.createFont();
font.setBold(true);
style.setFont(font);cell.setCellStyle(style); // 应用样式

 合并单元格

sheet.addMergedRegion(new CellRangeAddress(0, // 起始行0, // 结束行0, // 起始列3  // 结束列
));

处理日期与公式

// 设置日期格式
CellStyle dateStyle = workbook.createCellStyle();
dateStyle.setDataFormat(workbook.createDataFormat().getFormat("yyyy-MM-dd"));
cell.setCellValue(new Date());
cell.setCellStyle(dateStyle);// 设置公式
cell.setCellFormula("SUM(A1:A10)");

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词