Program:
import java.io.File;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
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;
import org.apache.poi.poifs. filesystem.POIFSFileSystem;
public class writeAppendExcel
{
private static String lOutputFileName = "C:\\Test\\Report3.xls";
public void writeExcel(String lOutputFileName,List<String> aOutputLines) {
File lFile = new File(lOutputFileName);
FileInputStream lFin = null;
HSSFWorkbook lWorkBook = null;
HSSFSheet lWorkSheet = null;
FileOutputStream lFout = null;
POIFSFileSystem lPOIfs = null;
if (lFile.exists()) {
try {
lFout = new FileOutputStream( lOutputFileName, true);
lFin = new FileInputStream( lOutputFileName);
lPOIfs = new POIFSFileSystem(lFin);
lWorkBook = new HSSFWorkbook(lPOIfs);
lWorkSheet = lWorkBook.getSheet("Sheet1");
} catch (IOException e) {
e.printStackTrace();
}
}
else {
// Create new file
try {
lFout = new FileOutputStream( lOutputFileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
lWorkBook = new HSSFWorkbook();
lWorkSheet = lWorkBook.createSheet("Sheet1" );
}
try {
for (String lValue : aOutputLines) {
if (lValue == null) {
System.out.println("=>NULL VALUE => " + lValue);
}
else {
StringBuffer lSqlLine = new StringBuffer( lValue);
HSSFRow lRow = lWorkSheet.createRow( lWorkSheet.getLastRowNum()+1);
System.out.println(" lWorkSheet.getLastRowNum() " + lWorkSheet.getLastRowNum());
HSSFCell lCell = lRow.createCell((short) 0);
lCell.setCellValue(lValue);
System.out.println(lValue);
}
}
lWorkBook.write(lFout);
lFout.flush();
}
catch (IOException e) {
n e.printStackTrace();
}
finally {
try {
lFout.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String args[])
{
List<String> aOutputLines = new ArrayList<String>();
aOutputLines.add("Good Bye1");
aOutputLines.add("Job1");
aOutputLines.add("finish1");
String name=(String) aOutputLines.get(0);
System.out.println(name);
System.out.println( aOutputLines.get(1));
System.out.println( aOutputLines.get(2));
writeAppendExcel poiWriteAppend = new writeAppendExcel ();
poiWriteAppend.writeExcel( lOutputFileName,aOutputLines);
}
}
No comments:
Post a Comment