org.apache.poi
apache.poi 可用于 word/ppt/excel等文件进行处理
详情见于 -> https://poi.apache.org/components/index.html 导航栏中Component APIs 应用指南
一、Excel (HSSF/XSSF)
1 public static void creatWorkbook()throws Exception{ 2 // 创建工作薄 3 Workbook wb = new HSSFWorkbook(); 4 // 创建表 5 CreationHelper createHelper = wb.getCreationHelper(); 6 Sheet sheet = wb.createSheet("new sheet"); 7 // 创建第一行 *************************** 8 Row row = sheet.createRow(0); 9 // 创建单元格 10 Cell cell = row.createCell(0); 11 // 插入单元格数值 (整数、小数、字符串、布尔型) 12 cell.setCellValue(1); 13 row.createCell(1).setCellValue(1.2); 14 row.createCell(2).setCellValue(createHelper.createRichTextString("This is a string")); 15 row.createCell(3).setCellValue(true); 16 // 创建第二行 * 时间 ************************* 17 Row row1 = sheet.createRow(1); 18 Cell cell1 = row1.createCell(0); 19 String localData = LocalDate.now().toString(); 20 cell1.setCellValue(createHelper.createRichTextString(localData)); 21 22 23 CellStyle cellStyle = wb.createCellStyle(); 24 cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("m/d/yy h:mm")); 25 cell1 = row1.createCell(1); 26 cell1.setCellValue(new Date()); 27 cell1.setCellStyle(cellStyle); 28 29 //you can also set date as java.util.Calendar 30 cell1 = row1.createCell(2); 31 cell1.setCellValue(Calendar.getInstance()); 32 cell1.setCellStyle(cellStyle); 33 row1.createCell(3).setCellType(CellType.ERROR); 34 35 // 输出文件 36 try (OutputStream fileOut = new FileOutputStream("D:\\资料\\exl\\workbook.xls")) { 37 wb.write(fileOut); 38 } 39 }
读取列宽 -> sheet.getColumnWidth(int index)
public static void main(String [] args) {
String filePath = "E:/Browers/测试查看默认100列.xls";
try{
FileInputStream fs = new FileInputStream(filePath);
HSSFWorkbook workbook = new HSSFWorkbook(fs);
HSSFSheet sheet = workbook.getSheetAt(0);
int lastRowIndex = sheet.getLastRowNum();
int lastColIndex = getLastColIndex(sheet,lastRowIndex);
for(int i = 0; i<lastColIndex ;i++){
System.out.println((sheet.getColumnWidth(i)/512)*100);
}
}catch (Exception e){
System.out.println("错误:" + e.getMessage());
}
}
private static int getLastColIndex(HSSFSheet sheet,int lastRowIndex){
int currIndex = -1;
for(int i = 0; i <= lastRowIndex; i++){
if(sheet.getRow(i) != null){
if(sheet.getRow(i).getLastCellNum() > currIndex){
currIndex = sheet.getRow(i).getLastCellNum();
}
}
}
return currIndex;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了