• JAVA用POI读取和创建2003和2007版本Excel


    1.添加maven依赖

            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi-ooxml</artifactId>
                <version>3.10-FINAL</version>
            </dependency>

    2.读取和创建2003和2007版本Excel示例

      1 package com.wyg.simple;
      2 
      3 import java.io.File;
      4 import java.io.FileInputStream;
      5 import java.io.FileOutputStream;
      6 import java.io.IOException;
      7 import java.text.DecimalFormat;
      8 import java.text.SimpleDateFormat;
      9 import java.util.LinkedList;
     10 import java.util.List;
     11 
     12 import org.apache.poi.hssf.usermodel.HSSFCellStyle;
     13 import org.apache.poi.hssf.usermodel.HSSFDataFormat;
     14 import org.apache.poi.hssf.usermodel.HSSFDateUtil;
     15 import org.apache.poi.hssf.usermodel.HSSFFont;
     16 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
     17 import org.apache.poi.hssf.util.HSSFColor;
     18 import org.apache.poi.ss.usermodel.Cell;
     19 import org.apache.poi.ss.usermodel.CellStyle;
     20 import org.apache.poi.ss.usermodel.Font;
     21 import org.apache.poi.ss.usermodel.Row;
     22 import org.apache.poi.ss.usermodel.Sheet;
     23 import org.apache.poi.ss.usermodel.Workbook;
     24 import org.apache.poi.xssf.usermodel.XSSFCell;
     25 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
     26 
     27 public class CreatAndReadExcel {
     28     private static String excel2007Path = "D:\temp\style_2007.xlsx";
     29     private static String excel2003Path = "D:\temp\style_2003.xls";
     30 
     31     public static void main(String[] args) throws Exception {
     32         creatExcel(excel2007Path, "2007");// 创建2007版Excel文件
     33         creatExcel(excel2003Path,"2003");// 创建2003版Excel文件
     34 
     35 //        List<List<Object>> excel2007List = readExcel(excel2007Path);// 读取2007版Excel文件
     36         List<List<Object>> excel2003List = readExcel(excel2003Path);// 读取2003版Excel文件
     37         System.out.println(excel2003List.toString());
     38     }
     39 
     40     /**
     41      * 创建Excel文件
     42      * 
     43      * @return
     44      * @throws IOException
     45      */
     46     public static void creatExcel(String excelPath, String version) throws IOException {
     47         // XSSFWork used for .xslx (>=2007), HSSWorkbook for 03 .xsl
     48         Workbook workbook = null;
     49         if (version.equals("2007")) {
     50             workbook = new XSSFWorkbook();// 创建 一个excel文档对象
     51         } else if (version.equals("2003")) {
     52             workbook = new HSSFWorkbook();// 创建 一个excel文档对象
     53         }
     54         Sheet sheet = workbook.createSheet("2007sheet");// 创建一个工作薄对象
     55         sheet.setColumnWidth(1, 10000);// 设置第二列的宽度为
     56 
     57         Row row0 = sheet.createRow(1);// 创建一个行对象,从0行开始
     58         row0.setHeightInPoints(23);// 设置行高23像素
     59         for (int i = 0; i < 11; i++) {
     60             Cell cell_1 = row0.createCell(i, Cell.CELL_TYPE_STRING);// 创建单元格,从0列开始
     61             cell_1.setCellValue("column" + i);// 写入单元格的值
     62             CellStyle style = getStyle(workbook);
     63             cell_1.setCellStyle(style);// 应用样式对象
     64             sheet.autoSizeColumn(i);// 自动调整列宽
     65         }
     66 
     67         FileOutputStream outputStream = new FileOutputStream(excelPath);
     68         workbook.write(outputStream);// 将文档对象写入文件输出流
     69 
     70         outputStream.close();// 关闭文件输出流
     71         System.out.println("创建成功 office excel");
     72     }
     73 
     74     /**
     75      * 设置样式
     76      * 
     77      * @param workbook
     78      * @return
     79      */
     80     private static CellStyle getStyle(Workbook workbook) {
     81         CellStyle style = workbook.createCellStyle();// 创建样式对象
     82         // 设置对齐方式
     83         style.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION);// 水平居中
     84         style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中
     85 
     86         // 设置边框
     87         style.setBorderTop(HSSFCellStyle.BORDER_THICK);// 顶部边框粗线
     88         style.setTopBorderColor(HSSFColor.RED.index);// 设置为红色
     89         style.setBorderBottom(HSSFCellStyle.BORDER_DOUBLE);// 底部边框双线
     90         style.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);// 左边边框
     91         style.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);// 右边边框
     92 
     93         style.setWrapText(true);// 设置单元格内容是否自动换行
     94         // 格式化日期
     95         style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
     96 
     97         // 设置单元格字体
     98         Font font = workbook.createFont(); // 创建字体对象
     99         font.setFontHeightInPoints((short) 14);// 设置字体大小
    100         font.setColor(HSSFColor.RED.index);// 设置字体颜色
    101         font.setFontName("宋体");// 设置为宋体字
    102         font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 设置粗体
    103         style.setFont(font);// 将字体加入到样式对象
    104 
    105         return style;
    106     }
    107 
    108     /**
    109      * 读取excel
    110      * 
    111      * @param fileName
    112      * @return 行<列>
    113      * @throws IOException
    114      */
    115 
    116     private static List<List<Object>> readExcel(String fileName) throws IOException {
    117         File file = new File(fileName);
    118         Workbook wb = null;
    119         if (fileName.endsWith(".xlsx")) {// 2007
    120             wb = new XSSFWorkbook(new FileInputStream(file));// 创建 一个excel文档对象
    121         } else if (fileName.endsWith(".xls")) {// 2003
    122             wb = new HSSFWorkbook(new FileInputStream(file));// 创建 一个excel文档对象
    123         }
    124 
    125         Sheet sheet = wb.getSheetAt(0);// 读取第一个sheet页表格内容
    126         Object value = null;
    127         Row row = null;
    128         Cell cell = null;
    129         System.out.println("读取office 2007 excel内容如下:");
    130 //        System.out.println(sheet.getPhysicalNumberOfRows());// 获取的是物理行数,也就是不包括那些空行(隔行)的情况。
    131 //        System.out.println(sheet.getLastRowNum());// 获取的是最后一行的编号(编号从0开始)
    132         //
    133         List<List<Object>> rowlist = new LinkedList<List<Object>>();
    134         for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
    135             row = sheet.getRow(i);
    136             if (row == null) {
    137                 continue;
    138             }
    139 
    140             //
    141             List<Object> cellList = new LinkedList<Object>();
    142             for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
    143                 cell = row.getCell(j);
    144                 if (cell == null) {
    145                     continue;
    146                 }
    147 
    148                 DecimalFormat df = new DecimalFormat("0");// 格式化 number String
    149                 DecimalFormat nf = new DecimalFormat("0.00");// 格式化数字
    150                 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 格式化日期字符串
    151                 switch (cell.getCellType()) {
    152                     case XSSFCell.CELL_TYPE_STRING:// 字符串——String type
    153                         value = cell.getStringCellValue();
    154                         break;
    155                     case XSSFCell.CELL_TYPE_NUMERIC:// 数字——Number type
    156                         if ("@".equals(cell.getCellStyle().getDataFormatString())) {
    157                             value = df.format(cell.getNumericCellValue());
    158                         } else if ("General".equals(cell.getCellStyle().getDataFormatString())) {
    159                             value = nf.format(cell.getNumericCellValue());
    160                         } else {
    161                             value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
    162                         }
    163                         break;
    164                     case XSSFCell.CELL_TYPE_BOOLEAN:// boolean——Boolean type
    165                         value = cell.getBooleanCellValue();
    166                         break;
    167                     case XSSFCell.CELL_TYPE_BLANK:// 空白——Blank type
    168                         value = "";
    169                         break;
    170                     default:// default type
    171                         value = cell.toString();
    172                 }
    173                 if (value == null || "".equals(value)) {
    174                     continue;
    175                 }
    176                 cellList.add(value);
    177             }
    178             rowlist.add(cellList);
    179         }
    180         return rowlist;
    181     }
    182 }

     

  • 相关阅读:
    Android SD卡读写文件
    Android 是什么
    Canvas 类
    Java IO流之字节流 FileInputStream
    Android中asset文件夹和raw文件夹区别
    随手收藏
    Java IO流
    Android私有文件资源文件的存取
    ubuntu 下的jdk安装
    Paint类
  • 原文地址:https://www.cnblogs.com/gangzi2013/p/5647162.html
Copyright © 2020-2023  润新知