|
在很多项目中,需要JAVA程序对Excel文件的操作,具体文档参见附件,以下为我写的一个例子,包括对Excel文件的读取和生成,希望对需要的朋友有点点帮助
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.Region;
import java.io.FileInputStream;
import java.io.*;
import java.util.Date;
import java.text.SimpleDateFormat;
public class Excel {
private static String fileName="E:/test.xls";
private String outfile="E:/out.xls";
private InputStream fileInput=null;
public Excel() {
}
/**
*Excel文件读取
*/
public void ReadExcel(){
String text="";
try{
fileInput=new FileInputStream(fileName);//构建输入流
HSSFWorkbook excelbook = new HSSFWorkbook(fileInput);// 创建对Excel工作簿文件的引用
HSSFSheet sheet = excelbook.getSheet("Sheet1");// 创建对工作表的引用。
//HSSFSheet sheet = excelbook.getSheetAt(0);与上同理
HSSFRow row = null;//行
HSSFCell cell=null;
int row_num=sheet.getLastRowNum();
System.out.println("row_num="+row_num);
int cell_num=0;
for(int i=0;i<row_num;i++){
row = sheet.getRow(i);
//判断空行,新插入的不是空行,注意:在统计行数时,空行没有被统计
while(row==null){
i++;
row_num++;
row = sheet.getRow(i);
}
cell_num=row.getLastCellNum();//获取当前行列数
System.out.print("cell:"+cell_num+" ");
for(int j=0;j<cell_num;j++){
cell = row.getCell((short)j);//单元格
if(cell!=null){//判断单元格是否为空
if(cell.getCellType()==HSSFCell.CELL_TYPE_NUMERIC){
if(HSSFDateUtil.isCellDateFormatted(cell)){//如果为日期格式,转换
Date date=cell.getDateCellValue();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");//设置日期转换格式
text=sdf.format(date);
}
else{//如果为纯数字格式,转换
double dou=(double)cell.getNumericCellValue();
text=String.valueOf(dou);
}
}
else{
text=cell.getStringCellValue(); }
}
else{
text="null";
}
System.out.print(text+" ,");
}
System.out.println();
}
}
catch(Exception ex){
System.out.println("EX: "+ex);
}
finally{//关闭流
if(fileInput!=null){
try{
fileInput.close();}
catch(Exception ex){
}
}
}
}
/**
* Excel文件输入
*/
public void CreateExcel(){
OutputStream fileOutput=null;
try{
HSSFWorkbook excelbook = new HSSFWorkbook();// 创建对Excel工作簿文件的引用
HSSFSheet sheet = excelbook.createSheet("Sheet1");// 创建对工作表的引用。
HSSFRow row = sheet.createRow((short)1);//定位行
row.setHeight((short)1000);//定义行高
HSSFCell cell=row.createCell((short)0);//定位单元格
cell.setEncoding(HSSFCell.ENCODING_UTF_16);//汉字需要设置编码
cell.setCellValue("数据输出测试!");
sheet.addMergedRegion(new Region(1,(short)0,1,(short)3));//合并单元格
HSSFCellStyle cellStyle = excelbook.createCellStyle();
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
cell.setCellStyle(cellStyle);
cell=row.createCell((short)5);
sheet.setColumnWidth((short)5,(short)3000);//第5列的宽度
cell.setCellValue("1.2345");
cellStyle.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
cell.setCellStyle(cellStyle);
fileOutput=new FileOutputStream(outfile);
excelbook.write(fileOutput);
System.out.print("YES!");
}
catch(Exception ex){
System.out.print("EX:"+ex);
}
finally{
if(fileOutput!=null){
try{
fileOutput.close();
}
catch(Exception ex){
System.out.print("EX1:"+ex);
}
}
}
}
} |
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有账号?立即注册
×
评分
-
查看全部评分
|