码迷,mamicode.com
首页 > 编程语言 > 详细

Java实现Excel文件读写操作

时间:2015-11-19 18:50:18      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:

写操作:

 

package com.zhao.poi;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class PoiExcle {
/*
*POI写入Excle文件内容
*/

public static void main(String[] args) {
//创建工作薄
HSSFWorkbook workbook=new HSSFWorkbook();
//创建sheet
HSSFSheet sheet=workbook.createSheet();
//创建第一行row
HSSFRow header=sheet.createRow(0);
//创建单元格并插入表头
HSSFCell cell=null;
String[] infos={"id","name","gender"};
for(int i=0;i<infos.length;i++){
cell=header.createCell(i);
cell.setCellValue(infos[i]);
}
//
HSSFRow body=null;
for(int i=1;i<=10;i++){
body=sheet.createRow(i);
cell=body.createCell(0);
cell.setCellValue(i+"");
cell=body.createCell(1);
cell.setCellValue("user_"+i);
cell=body.createCell(2);
cell.setCellValue(i+"");
}

//创建文件
File file=new File("D:\\poi_1119.xls");
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//文件输出流
try {
FileOutputStream stream=FileUtils.openOutputStream(file);
//写入
workbook.write(stream);
//关闭输出流
stream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

 

读操作:

package com.zhao.poi;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class PoiRead {

public static void main(String[] args) {
//获取文件
File file=new File("D:\\poi_1119.xls");
//文件输入流
try {
FileInputStream stream=FileUtils.openInputStream(file);
//工作薄
HSSFWorkbook workbook=new HSSFWorkbook(stream);
//Sheet
//HSSFSheet sheet=workbook.getSheet("sheet0");
HSSFSheet sheet=workbook.getSheetAt(0);
//
int firstRowNumber=0;
int lastRowNumber=sheet.getLastRowNum();
for(int i=firstRowNumber;i<lastRowNumber;i++){
HSSFRow row=sheet.getRow(i);
int firstCellNumber=0;
int lastCellNumber=row.getLastCellNum();
//
for(int j=firstCellNumber;j<lastCellNumber;j++){
HSSFCell cell=row.getCell(j);
String value=cell.getStringCellValue();
System.out.print(value+"\t");
}
System.out.println("");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

 

Java实现Excel文件读写操作

标签:

原文地址:http://www.cnblogs.com/zhao307/p/4978135.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!