JAVA 软件工程师教育系列教程
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class ExcelSample1 {
public static void main(String[] args) throws IOException {
//创建一个 excel 文件
HSSFWorkbook wb= new HSSFWorkbook();
FileOutputStream fileOut= new FileOutputStream("c:\\workbook.xls");
// FileOutputStream fileOut= new FileOutputStream("c:/workbook.xls");
wb.write(fileOut);
fileOut.close();
}
}
通过这个例子,我们在 c 盘下建立的是一个空白的 xls 文件(不是空文件)。在此基础
上,我们可以进一步看其它的例子。
import org.apache.poi.hssf.usermodel.*;
import java.io.FileOutputStream;
import java.io.IOException;
public class CreateCells
{
public static void main(String[] args) throws IOException
{
HSSFWorkbook wb = new HSSFWorkbook(); //建立新 HSSFWorkbook 对象
HSSFSheet sheet = wb.createSheet("new sheet"); //建立新的 sheet 对象
HSSFRow row = sheet.createRow((short)0);
//在 sheet 里创建一行,参数为行号(第一行,此处可想象成数组)
HSSFCell cell = row.createCell((short)0);
//在 row 里建立新 cell(单元格),参数为列号(第一列)
cell.setCellvalue(1); //设置 cell 的整数类型的值
row.createCell((short)1).setCellvalue(1.2); //设置 cell 浮点类型的值
row.createCell((short)2).setCellvalue("test"); //设置 cell 字符类型的值
row.createCell((short)3).setCellvalue(true); //设置 cell 布尔类型的值
HSSFCellStyle cellStyle = wb.createCellStyle(); //建立新的 cell 样式
cellStyle.setDataFormat(HSSFDataFormat. getBuiltinFormat("m/d/yy h:mm"));
//设置 cell 样式为定制的日期格式
HSSFCell dCell =row.createCell((short)4);
dCell.setCellvalue(new Date()); //设置 cell 为日期类型的值
dCell.setCellStyle(cellStyle); //设置该 cell 日期的显示格式
HSSFCell csCell =row.createCell((short)5);
csCell.setEncoding(HSSFCell.ENCODING_UTF_16);
//设置 cell 编码解决中文高位字节截断
csCell.setCellvalue("中文测试_Chinese Words Test"); //设置中西文结合字符串
3
评论0
最新资源