利用POI创建OpenOffice中的Excel文件
之所以称为OpenOffice的Excel文件,我发现了一个特点就是:
一些网站严格限定了文件必须为MS的Excel格式的话,用POI的HSSF创建的Excel就会不识别.不知道是什么原因,可能是版本的问题,据说HSSF(令人讨厌的电子表格格式)生成的是MS97的格式.但是97-2003的提示中明显的说明了MS的lib可以读取的啊.搞不懂这是为什么.
以下是Java的代码:
处理类:
![](https://cnherman.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://cnherman.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import org.apache.poi.hssf.usermodel.*;
/**
* @author qxhuang
*
*/
public class ExportToExcel {
private final static List<String[]> items=new ArrayList<String[]>();
/**
* Init Datas
* @param Address
* @param Zip
*/
public static void GenereateItem(String Address,String Zip){
items.add(new String[]{Address,Zip});
}
/**
* Export To Excel
* @param filepath
*/
public static void ExportExcel(String filepath)throws IOException{
HSSFWorkbook workbook=new HSSFWorkbook();
HSSFDataFormat format=workbook.createDataFormat();
HSSFSheet sheet= workbook.createSheet("sheet1");
HSSFRow row=sheet.createRow((short)0);
//add head cell
HSSFCell cell= row.createCell((short)0);
cell.setCellValue(new HSSFRichTextString("Address"));
cell= row.createCell((short)1);
cell.setCellValue(new HSSFRichTextString("Zip"));
if(items.size()>0){
for(int i=0;i<items.size();i++){
HSSFRow newrow=sheet.createRow(i+1);
String[] item=(String[])items.get(i);
for(int x=0;x<item.length;x++){
HSSFCell newcell=newrow.createCell((short)x);
newcell.setCellValue(new HSSFRichTextString(item[x].toString()));
}
}
}
for(int i=0;i<=items.size();i++){
sheet.autoSizeColumn((short)i);
}
FileOutputStream file=null;
try{
file=new FileOutputStream(filepath);
workbook.write(file);
file.close();
}catch(IOException ex){
workbook.write(file);
file.close();
ex.printStackTrace();
}
}
}
主函数:
![](https://cnherman.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://cnherman.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
import java.io.*;
import java.util.*;
/**
*
* @author qxhuang
*
*/
public class Main {
static BufferedReader input = new BufferedReader(new InputStreamReader(
System.in));
static String s = "";
public static void main(String[] args) throws IOException {
while (!s.toLowerCase().equals("done")) {
s = input.readLine();
if (s.indexOf(",") > -1) {
String[] temp = s.split(",");
if (temp.length == 2) {
ExportToExcel.GenereateItem(temp[0], temp[1]);
}
}
}
if (s.toLowerCase().equals("done")) {
File file = new File(".");
String path = file.getAbsolutePath();
String filename = path
+ new Date().toString().replace(" ", "").replace(":", "")
+ ".xls";
try {
ExportToExcel.ExportExcel(filename);
System.out
.println("Create Complete!! file name is " + filename);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
input.readLine();
}
/*
* (non-Java-doc)
*
* @see java.lang.Object#Object()
*/
public Main() {
super();
}
}
所需要的JAR在:
http://poi.apache.org/
H.Wong
-2010