使用POI hssf WritableWorkbook在Excel中导出数据

时间:2012-06-25 21:30:25

标签: java jsp apache-poi

我有这个DAO ..

public class AreaDAO {

    private Database database;

    public AreaDAO(Database database) {
        this.database = database;
    }

    public List<Area> list() throws SQLException {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        List<Area> areas = new ArrayList<Area>();

        try {
            connection = database.getConnection();
            statement = connection.prepareStatement("select distinct img_hub, country from ifs_db limit 50");
            resultSet = statement.executeQuery();
            while (resultSet.next()) {
                Area area = new Area();
                area.setImg_hub(resultSet.getString("img_hub"));
                area.setCountry(resultSet.getString("country"));
                areas.add(area);
            }
        } finally {
            if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {}
            if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
            if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
        }

        return areas;
    }
}

这会生成一个数据列表......

如何通过点击链接让用户下载excel中的所有数据..

我研究了我们并发现了这个......(由BalusC提供)

    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-Disposition", "attachment; filename=name.xls");
    WritableWorkbook workBook  = Workbook.createWorkbook(response.getOutputStream());

我把它放到我的servlet上,我怎么只是得到一张空白的工作表...我怎么能用它,所以我可以让用户下载

1 个答案:

答案 0 :(得分:3)

我知道您在this question上提及我的回答?请注意// ...行,您应该使用数据库中的数据填充工作簿。这个问题的OP已经知道了,所以为了简洁起见省略了它。

您可以在POI HSSF自己的网站a quick guide上找到如何使用API​​。

以下是如何使用单元格创建工作表的启动示例。

response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=name.xls");
WritableWorkbook workbook = Workbook.createWorkbook(response.getOutputStream());
WritableSheet sheet = workbook.createSheet("Sheet1", 0);
sheet.addCell(new Label(0, 0, "Hello World"));
// ...
workbook.write();
workbook.close();

您可以在迭代List<Area>时添加单元格。 E.g。

for (int i = 0; i < list.size(); i++) {
    Area area = list.get(i);
    sheet.addCell(new Label(0, i, area.getImgHub()));
    sheet.addCell(new Label(1, i, area.getCountry()));
}