poi导入导出excel文件.doc
文本预览下载声明
web中使用POI导入导出EXCEL文件的例子
struts1.x的例子,struts2.x可以参考自己修改
1.action的写法
import java.io.*;
import java.sql.*;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.*;
import org.apache.struts.action.*;
import org.apache.struts.upload.FormFile;
import mons.beanutils.BeanUtils;
public class Action {
/**//*
* 把数据库中的字段导入到Excel ,并生成Excel文档
**/
public ActionForward getDownload(ActionMapping actionMapping,
ActionForm actionForm, HttpServletRequest request,
HttpServletResponse response) throws Exception {
Form fm = (Form) actionForm;
// Excel 文件存放在服务器的相对路径下
String outputFile = request.getRealPath(/tmp/Excel.xls);
try {
// 创建新的Excel 工作簿
HSSFWorkbook workbook = new HSSFWorkbook();
// 在Excel 工作簿中建一工作表
HSSFSheet sheet = workbook.createSheet(Sheet1);
// 设置单元格格式(文本)
HSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat(@));
// 在索引0的位置创建行(第一行)
HSSFRow row = sheet.createRow((short) 0);
HSSFCell cell1 = row.createCell((short) 0);// 第一列
HSSFCell cell2 = row.createCell((short) 1);
HSSFCell cell3 = row.createCell((short) 2);
// 定义单元格为字符串类型
cell1.setCellType(HSSFCell.CELL_TYPE_STRING);
cell2.setCellType(HSSFCell.CELL_TYPE_STRING);
cell3.setCellType(HSSFCell.CELL_TYPE_STRING);
cell1.setEncoding(HSSFCell.ENCODING_UTF_16);
cell2.setEncoding(HSSFCell.ENCODING_UTF_16);
cell3.setEncoding(HSSFCell.ENCODING_UTF_16);
// 在单元格中输入数据
cell1.setCellValue(姓名);
cell2.setCellValue(性别);
cell3.setCellValue(年龄);
Connection connection = session.connection();
String sql = Select , t.sex, t.age from table t where t.sex = ?;
try {
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, fm.getSex());// 传入查询条件
ResultSet rs = ps.executeQuery();// 查询结果存入rs
mit();// 执行SQL
while (rs.next()) {
//
显示全部