[java]代码库
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package excel;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import java.io.FileInputStream;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
/**
*
* @author Administrator
*/
public class ExcelUtil
{
public String filePath = "e:\\workbook.xls";
public void newWordBook()
{
HSSFWorkbook wb = new HSSFWorkbook();
try
{
FileOutputStream fileOut = new FileOutputStream (filePath);
wb.write (fileOut);
fileOut.close();
}
catch (FileNotFoundException ex)
{
System.out.println (ex.getMessage() );
}
catch (IOException ex)
{
System.out.println (ex.getMessage() );
}
}
/**
* 创建空白文件
*/
public void newSheet()
{
HSSFWorkbook wb = new HSSFWorkbook();
wb.createSheet ("第一页");
wb.createSheet ("第二页");
try
{
FileOutputStream fileOut = new FileOutputStream (filePath);
wb.write (fileOut);
fileOut.close();
}
catch (FileNotFoundException ex)
{
System.out.println (ex.getMessage() );
}
catch (IOException ex)
{
System.out.println (ex.getMessage() );
}
}
private void saveWorkBook (HSSFWorkbook wb)
{
try
{
FileOutputStream fileOut = new FileOutputStream (filePath);
wb.write (fileOut);
fileOut.close();
}
catch (FileNotFoundException ex)
{
System.out.println (ex.getMessage() );
}
catch (IOException ex)
{
System.out.println (ex.getMessage() );
}
}
private HSSFWorkbook getWorkBook (String filePath)
{
try
{
FileInputStream fileIn = new FileInputStream (filePath);
HSSFWorkbook wb = new HSSFWorkbook (fileIn);
fileIn.close();
return wb;
}
catch (IOException ex)
{
System.out.println (ex.getMessage() );
return null;
}
}
private HSSFCell getCell (HSSFSheet sheet, int rowIndex, short columnIndex)
{
HSSFRow row = sheet.getRow (rowIndex);
if (row == null)
{
row = sheet.createRow (rowIndex);
}
HSSFCell cell = row.getCell (columnIndex);
if (cell == null)
{
cell = row.createCell ( (short) columnIndex);
}
return cell;
}
/**
* 写数据
* @param file
*/
public void writeData (String file)
{
//创建工作薄
HSSFWorkbook wb = getWorkBook (file);
if (wb == null)
{
return;
}
//获取工作表
HSSFSheet sheet = wb.getSheetAt (0);
if (sheet == null)
{
sheet = wb.createSheet ("第一页");
}
HSSFCell cell = getCell (sheet, 0, (short) 0);
//数值
cell.setCellValue (123);
//字符串
HSSFRichTextString str = new HSSFRichTextString ("你好");
cell = getCell (sheet, 0, (short) 1);
cell.setCellValue (str);
//保存
saveWorkBook (wb);
}
public static void main (String[] args)
{
ExcelUtil excel = new ExcelUtil();
excel.writeData (excel.filePath);
}
}