Java操作excel编程后心得
最近写了个简单的使用POI 包 生成Excel 程序虽然不复杂,但还是总结出一点编程心得。
首先编程先要有个大致的思路 比如我写了一列数据要以excel.xls写出 我先想到要操作表得有相应的工具把它映射成对象的形式才能在程序里操作使用,幸好Apache 的开源项目上 有个POI 包,里面是开发者发部上去的专门操作 多种文本的依赖的jar包及其源码(在此由衷的感谢Apache项目的开发人员) 把它下载下来再项目中导入这时有POI的支持就可以对文档操作了,
然后在项目中找要操作的对象(如表单,表格,样式)借助API 这样就比较顺利的进行开发了
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
public class com {
/**
* @param args
* 生成MyExcle
* @throws FileNotFoundException
*/
public static void main(String[] args) {
int begin=1;
int end=50;
//创建表
HSSFWorkbook hssfworkbook=new HSSFWorkbook();
//创建表单(表结构)
HSSFSheet hssfsheet=hssfworkbook.createSheet();
HSSFCellStyle hssfcellstyleHead=hssfworkbook.createCellStyle();
HSSFCellStyle hssfcellstyleContext=hssfworkbook.createCellStyle();
//创建字体样式
HSSFFont font1=hssfworkbook.createFont();
HSSFFont font2=hssfworkbook.createFont();
font1.setFontHeightInPoints((short)12);
font1.setColor((short)2);
font1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
font2.setFontHeightInPoints((short)10);
font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
hssfcellstyleHead.setFont(font1);
hssfcellstyleContext.setFont(font2);
int rowIndex=0;
int colIndex=0;
HSSFRow hssfrow=hssfsheet.createRow(rowIndex++);
HSSFCell hssfcell=hssfrow.createCell((short)colIndex++);
String [] headTitle={"第1列头部","第2列头部","第3列头部"};
for(int i=0;i<headTitle.length;i++)
{
hssfcell=hssfrow.createCell((short)i);
hssfcell.setCellStyle(hssfcellstyleHead);
hssfcell.setCellValue(new HSSFRichTextString(headTitle[i]));
}
for(int i=begin;i<end ;i++)
{
hssfrow=hssfsheet.createRow(rowIndex++);
int index=0;
HSSFCell cell4=hssfrow.createCell((short)index++);
HSSFCell cell5=hssfrow.createCell((short)index++);
HSSFCell cell6=hssfrow.createCell((short)index++);
cell4.setCellStyle(hssfcellstyleContext);
cell5.setCellStyle(hssfcellstyleContext);
cell6.setCellStyle(hssfcellstyleContext);
cell4.setCellValue(new HSSFRichTextString("第1列数据"));
cell5.setCellValue(new HSSFRichTextString("第2列数据"));
cell6.setCellValue(new HSSFRichTextString("第3列数据"));
}
for(int i=0;i<3;i++)
{
hssfsheet.autoSizeColumn((short)i);
}
File file =new File("F:\\Myexel.xls");
FileOutputStream fos;
try {
fos=new FileOutputStream(file);
hssfworkbook.write(fos);
System.out.println("sccessfully");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}