poi读写excel和word(二)

2014-11-24 02:33:25 · 作者: · 浏览: 1

HSSFSheet sheet = workbook.createSheet("第一页");
//HSSFSheet sheet = workbook.createSheet();

// 在指定的索引处创建一行
HSSFRow row = sheet.createRow((short) 0);

//在指定索引处创建单元格
HSSFCell id = row.createCell((short) 0);
// 定义单元格为字符串类型
id.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
// 在单元格中输入一些内容,HSSFRichTextString可以解决乱码问题
HSSFRichTextString idContent = new HSSFRichTextString("用户id号");
id.setCellValue(idContent);

HSSFCell name = row.createCell((short) 1);
name.setCellType(HSSFCell.CELL_TYPE_STRING);
HSSFRichTextString nameContent = new HSSFRichTextString("用户名");
name.setCellValue(nameContent);

HSSFCell password = row.createCell((short) 2);
password.setCellType(HSSFCell.CELL_TYPE_STRING);
HSSFRichTextString passwordContent = new HSSFRichTextString("用户密码");
password.setCellValue(passwordContent);

// 新建一输出文件流
FileOutputStream out = new FileOutputStream(fileToWrite);
// 把相应的Excel 工作簿存盘
workbook.write(out);
out.flush();
// 操作结束,关闭文件
out.close();

System.out.println("文件生成..." + fileToWrite);
}
}
package poi.xls;
import java.io.FileOutputStream;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
/**
* 利用POI实现向excel中写入内容
*/
public class XLSWriter {

public static String fileToWrite = "c:/test.xls";

public static void main(String[] args) throws Exception {
// 创建新的Excel 工作簿
HSSFWorkbook workbook = new HSSFWorkbook();

// 在Excel工作簿中建一工作表,其名为缺省值
HSSFSheet sheet = workbook.createSheet("第一页");
//HSSFSheet sheet = workbook.createSheet();
// 在指定的索引处创建一行
HSSFRow row = sheet.createRow((short) 0);
//在指定索引处创建单元格
HSSFCell id = row.createCell((short) 0);
// 定义单元格为字符串类型
id.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
// 在单元格中输入一些内容,HSSFRichTextString可以解决乱码问题
HSSFRichTextString idContent = new HSSFRichTextString("用户id号");
id.setCellValue(idContent);
HSSFCell name = row.createCell((short) 1);
name.setCellType(HSSFCell.CELL_TYPE_STRING);
HSSFRichTextString nameContent = new HSSFRichTextString("用户名");
name.setCellValue(nameContent);
HSSFCell password = row.createCell((short) 2);
password.setCellType(HSSFCell.CELL_TYPE_STRING);
HSSFRichTextString passwordContent = new HSSFRichTextString("用户密码");
password.setCellValue(passwordContent);
// 新建一输出文件流
FileOutputStream out = new FileOutputStream(fileToWrite);
// 把相应的Excel 工作簿存盘
workbook.write(out);
out.flush();
// 操作结束,关闭文件
out.close();
System.out.println("文件生成..." + fileToWrite);
}
}
读取word内容:
view plaincopy to clipboardprint
package poi.doc;

/**
* 利用POI实现从word中读取内容
*/
import java.io.FileInputStream;

import org.apache.poi.hwpf.extractor.WordExtractor;

public class DOCReader {

public static String fileToRead = "c:/test.doc";

public static void main(String[] args) throws Exception{
// 创建输入流读取DOC文件
FileInputStream in = new FileInputStream(fileToRead);