java poi 操作excel

1.pom文件

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

2.java代码

写入xls

public static void createXls() {
	HSSFWorkbook wb = new HSSFWorkbook();    
    HSSFSheet sheet = wb.createSheet();    
    HSSFRow row = sheet.createRow(0);    
    row.createCell(0).setCellValue("123");
    row.createCell(1).setCellValue("456");
        
    row = sheet.createRow(1);    
    row.createCell(0).setCellValue("789");
    row.createCell(1).setCellValue("000");

    try{    
        FileOutputStream fout = new FileOutputStream("1.xls");    
        wb.write(fout);    
        fout.close();    
    }catch (IOException e){    
        e.printStackTrace();    
    }   
}

 

写入xlsx

 

public static void createXlsx() {
		XSSFWorkbook hwb = new XSSFWorkbook();
		XSSFSheet sheet = hwb.createSheet();
		XSSFRow row = sheet.createRow(0);
		row.createCell(0).setCellValue("ABC");
		row.createCell(1).setCellValue("DEF");
		row = sheet.createRow(1);
		row.createCell(0).setCellValue("HIJ");
		row.createCell(1).setCellValue("KLM");
		
		OutputStream out;
		try {
			out = new FileOutputStream(xlsxname);
			hwb.write(out);
			out.close();
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

读取xls

public static void readXls() {
		FileInputStream fileInput;
		try {
			fileInput = new FileInputStream(xlsname);
			POIFSFileSystem ts = new POIFSFileSystem(fileInput);
			HSSFWorkbook workbook = new HSSFWorkbook(ts);
			HSSFSheet sh = workbook.getSheetAt(0);
			
			for(int i=0;i<sh.getPhysicalNumberOfRows();i++){
				Row row = sh.getRow(i);
				for(int j=0;j<row.getPhysicalNumberOfCells();j++){
					System.out.print(row.getCell(j).getStringCellValue()+" ");
				}
				System.out.println();
			}
			
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

 

读取xlsx

 

public static void readXlsx() {

		InputStream is;
		try {
			is = new FileInputStream(xlsxname);
			XSSFWorkbook xwb = new XSSFWorkbook(is);
			XSSFSheet sheet = xwb.getSheetAt(0);
			XSSFRow row;

			System.out.println(">>>>>>>>>>>>>>>>>>>>>>>");
			for (int i = 0; i < sheet.getPhysicalNumberOfRows(); i++) {
				row = sheet.getRow(i);
				for(int j=0;j<row.getPhysicalNumberOfCells();j++){
					XSSFCell cell=row.getCell(j);
					System.out.print(cell+" ");
				}
				System.out.println();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值