Java操作Excel之Poi

创建excel
public class PoiWriter{
    public static void main(String[] args) throws Exception{
        //获取Workbook对象
        Workbook workbook = new HSSFWorkbook();
        //创建一个sheet页面
        Sheet sheet = workbook.createSheet("第一页");
        //在sheet页面中创建一行,行数从0开始
        Row row = sheet.createRow(0);
        //在这一行创建单元格(列),在第一行,第一列填充数据
        Cell cell = row.createCell(0);
        cell.setCellValue("hello poi...");
        //cell.setCellValue(new HSSFRichTextString("hello poi..."));  // 设置值
        //获取xls文档的输出流对象
        OutputStream os = new FileOutputStream("e:/poiDemo1.xls");
        //生成poi文档
        workbook.write(os);
        //释放资源
        os.close();
    }
    
    //创建一个单元格并填充日期类型数据
    private static void createDateCell(Workbook workbook,Row row,short column){
        //获取CellStyle对象
        CellStyle cellStyle = workbook.createCellStyle();
        //获取CreationHelper对象
        CreationHelper helper = workbook.getCreationHelper();
        //设置日期的格式
        cellStyle.setDataFormat(helper.createDataFormat().getFormat("yyyy-MM-dd"));
        //创建单元格
        Cell cell = row.createCell(column);
        cell.setCellStyle(cellStyle);
        cell.setCellValue(new Date());
      
    }
    
    //创建一个单元格,并对同一个单元格的数据换行(row不变)
    private static void setAutoWrap(Workbook workbook,Row row,short column){
        //获取CellStyle对象
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setWrapText(true);	//开启解析"\n"换行符
        //创建单元格
        Cell cell = row.createCell(column);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("测试数据第一行 \n 测试数据第二行"); 
    }
    
    //创建一个单元格并为其设定指定的对其方式
    //createCell(wb,row,(short)2,HSSFCellStyle.ALIGN_CENTER,HSSFCellStyle.VERTICAL_BOTTOM);
    private static void createAlignCell(Workbook workbook,Row row,short column,short halign,short valign){	
        CellStyle cellStyle = workbook.createCellStyle(); // 创建单元格样式
        cellStyle.setAlignment(halign);  // 设置单元格水平方向对其方式
        cellStyle.setVerticalAlignment(valign); // 设置单元格垂直方向对其方式
        Cell cell=row.createCell(column);  // 创建单元格
        cell.setCellStyle(cellStyle); // 设置单元格样式
        cell.setCellValue("测试数据");
	}
    
    //单元格边框处理
     private static void setBorder(Workbook workbook,Row row,short column){
         //获取CellStyle对象
         CellStyle cellStyle = workbook.createCellStyle();
         cellStyle.setBorderTop(CellStyle.BORDER_MEDIUM_DASHED); // 上边边框
         cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());  // 上边边框颜色
         cellStyle.setBorderBottom(CellStyle.BORDER_THIN); // 底部边框
         cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex()); // 底部边框颜色
         cellStyle.setBorderLeft(CellStyle.BORDER_THIN);  // 左边边框
         cellStyle.setLeftBorderColor(IndexedColors.GREEN.getIndex()); // 左边边框颜色
         cellStyle.setBorderRight(CellStyle.BORDER_THIN); // 右边边框
         cellStyle.setRightBorderColor(IndexedColors.BLUE.getIndex());  // 右边边框颜色
         Cell cell = row.createCell(column);
         cell.setCellStyle(cellStyle);
         cell.setCellValue("测试数据");
    }
    
    //设置单元格背景色,前景色
    private static void setGroundColor(Workbook workbook,Row row,short column){
         //获取CellStyle对象
         CellStyle cellStyle = workbook.createCellStyle();
         cellStyle.setFillBackgroundColor(IndexedColors.AQUA.getIndex()); // 背景色
         cellStyle.setFillForegroundColor(IndexedColors.RED.getIndex()); // 前景色
         cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);  //前进背景样式
         Cell cell = row.createCell(column);
         cell.setCellStyle(cellStyle);
         cell.setCellValue("测试数据");
    }
    
    //合并单元格,org.apache.poi.ss.util.CellRangeAddress
    private static void mergeRegion(Sheet sheet,
       		int firstRow, int lastRow, int firstCol, int lastCol){
         sheet.addMergedRegion(new CellRangeAddress(
				firstRow, // 起始行
				lastRow, // 结束行
				firstCol, // 其实列
				lastCol  // 结束列
		));
    }
    
    //设置字体的样式
    private static void setFont(Workbook workbook,Row row,short column){
        // 创建一个字体处理类
		Font font = workbook.createFont();
		font.setFontHeightInPoints((short)24);	//字体大小
		font.setFontName("宋体");	//字体格式
		font.setItalic(true);		//斜体
		font.setStrikeout(true);	//删除线
		CellStyle style = workbook.createCellStyle();
		style.setFont(font);
		Cell cell = row.createCell(column);
		cell.setCellStyle(style);
    }	
    
    //格式化数字
     private static void createNumCell(Workbook workbook,Row row,short column){
         CellStyle style = workbook.createCellStyle();
         DataFormat format = workbook.createDataFormat();
         //设置数据格式,四舍五入保留一位小数,eg: 9999.0
         //#,##0.0表示以美元的方式表示数字,并保留一位小数,eg: 9,999.0
         style.setDataFormat(format.getFormat("0.0"));
         Cell cell = row.createCell(column);
         cell.setCellStyle(style);
         cell.setCellValue(9999.01);
    }
}
读取excel
1.遍历每一行每一列读取excel
public class PoiReader1{
    public static void main(String[] args) throws Exception{
        //获取xls文件输入流对象
        InputStream is = new FileInputStream("e:/poiDemo1.xls");
        //创建POIFSFileSystem对象
        POIFSFileSystem system = new POIFSFileSystem(is);
        //获取xls文件的HSSFWorkbook对象
        HSSFWorkbook workbook = new HSSFWorkbook(system);
        //获取第一页的sheet对象
        HSSFSheet sheet = workbook.getSheetAt(0);
        if(sheet==null){
            return;
        }
        //获取第一页的所有行
        int rowNum = sheet.getLastRowNum();
        for( int i = 0 ; i < rowNum ; i++){
           //获取其中的一行
           HSSFRow row = sheet.getRow(i);
            if(row==null){
                continue;
            }
            //获取这一行的列数
           short cellNum = row.getLastCellNum();
            for(int m = 0; m<cellNum ;m++){
                //获取每一行的每一个单元格对象
                HSSFCell cell = row.getCell(m);
                if(cell==null){
                	continue;
            	}
                System.out.print(" " + getValue(cell));
            }
            System.out.println();
        } 
    }
    private static String getValue(HSSFCell cell){
        //获取单元格数据的数据类型
        int cellType = cell.getCellType();
        if(cellType==HSSFCell.CELL_TYPE_BOOLEAN){
            //boolean类型
            return String.valueOf(cell.getBooleanCellValue());
        }else if(cellType == HSSFCell.CELL_TYPE_NUMERIC){
            return String.valueOf(cell.getNumericCellValue());
        }else{
            return String.valueOf(cell.getStringCellValue());
        }
    }
}

2.直接抽取excel的全部文本信息
public class PoiReader1{
    public static void main(String[] args) throws Exception{
        //获取xls文件输入流对象
        InputStream is = new FileInputStream("e:/poiDemo1.xls");
        //创建POIFSFileSystem对象
        POIFSFileSystem system = new POIFSFileSystem(is);
        //获取xls文件的HSSFWorkbook对象
        HSSFWorkbook workbook = new HSSFWorkbook(system);
        //获取ExcelExtractor对象,org.apache.poi.hssf.extractor.ExcelExtractor
        ExcelExtractor extractor = new ExcelExtractor(workbook);
        String text = extractor.getText();
        System.out.println(text);
     }
}

3.读取excel后修改excel
public static void main(String[] args) throws Exception{
		InputStream is =new FileInputStream("e:/poiDemo1.xls");
		POIFSFileSystem system = new POIFSFileSystem(is);
		Workbook workbook = new HSSFWorkbook(system);
		Sheet sheet = workbook.getSheetAt(0);  // 获取第一个Sheet页
		Row row = sheet.getRow(0); // 获取第一行
		Cell cell = row.getCell(0); // 获取单元格
		if(cell==null){
			cell=row.createCell(3);
		}
		cell.setCellType(Cell.CELL_TYPE_STRING);
		cell.setCellValue("测试单元格");
		FileOutputStream fs = new FileOutputStream("e:/poiDemo1.xls");
		workbook.write(fs);
		fs.close();
	}
}
Apache Poi坐标
	Apache POI是Apache提供的使用Java程序对Microsoft Office格式文档操作的API
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.8</version>
</dependency>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值