1、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.*;im
2、port 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 = (Fo
3、rm) 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();cellStyl
4、e.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);c
5、ell2.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
6、(“年龄“);Connection connection = session.connection();String sql = “Select t.name, 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();/ 查询结果存入 mit();/ 执行 SQLwhile (rs.next() /设置 j 行
7、从第二行开始int j = 1;row = sheet.createRow(short) j);/设置 i 列从第二列开始for (int i = 1; i function upload(obj)if(confirm(“您现在选择的是 XXX,您确定要导入吗?“)var uploadfile = document.all.uploadfile.value;if(null = uploadfile) |( “ = uploadfile)alert(“上传文件没有指定!“);return false;obj.action = ;obj.submit();4.下载页面 Download.jsp下传文件 “ name=“下载“下载