Apache POI

一、poi介绍

Apache POI是Apache软件基金会的提供的一套操作office办公文档的API,可以使用Java程序对Microsoft Office格式文档进行读和写的操作。

二、poi结构

HSSF - 提供对Microsoft Excel格式文档读与写的操作
XSSF - 提供对Microsoft Excel OOXML格式文档读与写的操作
HWPF - 提供对Microsoft Word格式文档读与写的操作
HSLF - 提供对Microsoft PowerPoint格式文档读与写的操作
HDGF - 提供对Microsoft Visio格式文档读与写的操作

三、下面演示一下Demo

(向磁盘输出一个excel文件)

  1. import java.io.File;
  2. import java.io.FileOutputStream;
  3. import org.apache.poi.hssf.usermodel.HSSFCellStyle;
  4. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  5. import org.apache.poi.ss.usermodel.Cell;
  6. import org.apache.poi.ss.usermodel.CellStyle;
  7. import org.apache.poi.ss.usermodel.Font;
  8. import org.apache.poi.ss.usermodel.Row;
  9. import org.apache.poi.ss.usermodel.Sheet;
  10. import org.apache.poi.ss.usermodel.Workbook;
  11. public class demo {
  12. public static void main(String[] args) {
  13. Sheet sheet = null;
  14. // 创建一个excel文件并指定文件名
  15. File file = new File("D://demoPoi.xls");
  16. @SuppressWarnings("resource")
  17. Workbook workbook = new HSSFWorkbook();
  18. // 标题行样式
  19. CellStyle titleStyle = workbook.createCellStyle();
  20. titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  21. Font titleFont = workbook.createFont();
  22. titleFont.setFontHeightInPoints((short) 15);
  23. titleFont.setBoldweight((short) 100);
  24. titleStyle.setFont(titleFont);
  25. // 创建sheet
  26. sheet = workbook.createSheet("poi测例");
  27. // 创建标题行 行数从0开始 从第一列开始
  28. Row titleRow = sheet.createRow(0);
  29. titleRow.createCell(0).setCellValue("序号");
  30. titleRow.getCell(0).setCellStyle(titleStyle);
  31. titleRow.createCell(1).setCellValue("姓名");
  32. titleRow.getCell(1).setCellStyle(titleStyle);
  33. titleRow.createCell(2).setCellValue("分数");
  34. titleRow.getCell(2).setCellStyle(titleStyle);
  35. Row row = sheet.createRow(1);
  36. // 创建第一行数据
  37. Cell createCell = row.createCell(0);
  38. createCell.setCellValue(1);
  39. Cell createCell2 = row.createCell(1);
  40. createCell2.setCellValue("xixi");
  41. Cell createCell3 = row.createCell(2);
  42. createCell3.setCellValue(90);
  43. FileOutputStream outputStream;
  44. try {//创建文件输出流并输出
  45. outputStream = new FileOutputStream(file);
  46. workbook.write(outputStream);
  47. } catch (Exception e) {
  48. e.printStackTrace();
  49. }
  50. }
  51. }

效果如下:
在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,25人围观)

还没有评论,来说两句吧...

相关阅读