excel导出文件

// 创建一个新的excel文件,并将数据导入进去
	public static void writeExcel(ResultSet rs, String fileName,
			HttpServletResponse response) throws SQLException, IOException,
			RowsExceededException, WriteException {
		ResultSetMetaData rsmd = rs.getMetaData();
		// 获得导出数据的列数
		int columnCount = rsmd.getColumnCount();
		Vector columnNames = new Vector();
		for (int i = 1; i <= columnCount; i++) {
			// 获得指定列表的名字
			columnNames.add(rsmd.getColumnName(i));
		}
		Vector dataOfRows = new Vector();
		dataOfRows.add(columnNames);
		while (rs.next()) {
			Vector columnValues = new Vector();
			for (int i = 1; i <= columnCount; i++) {
				try {
					String columnValue = rs.getString(i);
					if (columnValue == null) {
						columnValue = "";
					}
					columnValues.add(columnValue);
				} catch (Exception e) {
					// 时间为空时会出异常
					columnValues.add("");
				}
			}
			dataOfRows.add(columnValues);
		}
		response.setContentType("application/x-msdownload");
		String time = (new Timestamp(System.currentTimeMillis())).toString()
				.substring(2, 10).replaceAll("-", "");
		// 定义打印出来后的报表名
		String dispposition = "=?UTF-8?Q?attachment; filename="
				+ Utilities.toUtf8String(fileName + time)
				+ ".xls";
		response.setHeader("Content-Disposition", dispposition);
		OutputStream os = response.getOutputStream();
		jxl.write.WritableWorkbook wwb = Workbook.createWorkbook(os);
		jxl.write.WritableSheet ws = wwb.createSheet(fileName, 0);
		for (int i = 0; i < dataOfRows.size(); i++) {
			for (int j = 0; j < columnCount; j++) {
				Label label = new Label(j, i, ((Vector) dataOfRows.get(i)).get(
						j).toString());
				ws.addCell(label);
			}
		}
		// 关闭Excel工作薄对象
		wwb.write();
		wwb.close();
		os.close();
	}

 原先只写过导入 这次看了下同事写的导出很通用就放了上来 jxl包不用我介绍了吧 算了还是传1个上来大家也不用在别处找了

你可能感兴趣的:(JAVA文章,Excel,OS,J#,工作)