poi如何操作,word,excel

2024-12-30 04:59:17
推荐回答(1个)
回答1:

参考下POI的demo

package excel;

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

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 ExcelPOIDemo
{
public static void main(String[] args)
{
// 生成excel代码
// HSSFWorkbook wb = new HSSFWorkbook();
// HSSFSheet sheet = wb.createSheet("new sheet");
// HSSFRow row = null;
// HSSFCell cell=null;
// for(long i =0;i<=100;i++){
//
// row = sheet.createRow((short)i); //创建一个行
// for(int j =0;j<10;j++){
//
// cell = row.createCell((short)j); //创建单元格
// cell.setEncoding(HSSFCell.ENCODING_UTF_16);
// if(i==0){
// cell.setCellValue("ddd"); //设定单元格的值
// }else{
// cell.setCellValue("dddd"); //设定单元格的值
// }
// }
// }
// //写到excel中!
// FileOutputStream fileOut;
// try
// {
// fileOut = new FileOutputStream(new File("d:\\excel.xls"));
// wb.write(fileOut);
// fileOut.close();
// }
// catch (IOException e)
// {
// // TODO Auto-generated catch block
// } //关闭文件输出流

ExcelPOIDemo.poi();

}

public static void poi()
{
// 创建HSSFWorkbook对象
HSSFWorkbook wb = new HSSFWorkbook();
// 创建HSSFSheet对象
HSSFSheet sheet = wb.createSheet("sheet0");
// 创建HSSFRow对象
HSSFRow row = null;
OutputStream out = null;
for (int i = 0; i < 10; i++)
{
row = sheet.createRow((short)0);
// 创建HSSFCell对象
HSSFCell cell=row.createCell((short)0);
// 用来处理中文问题
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
// 设置单元格的值
cell.setCellValue("单元格中的中文");
// 定义你需要的输出流
out = null;;

}
try
{
out = new FileOutputStream("d:\\viwo.xls");
}
catch (FileNotFoundException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
// 输出Excel
try
{
wb.write(out);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
try
{
out.flush();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}