java如何导出表格

1.在action中添加两个属性并添加get和set方法

private ByteArrayOutputStream baos;
private ByteArrayInputStream bais;

2.在action里面增加如下代码

    /**
    * get the InputStream
    *
    * @return
    */
    public InputStream getInputStream() {
      InputStream is = bais;
    return is;
    }

3.在action中添加导出代码

List slist=new ArrayList();

//caiwuduizhangdanchaxunjilu.xls文件放到本地项目目录下的excelMould文件夹下面

InputStream is = new FileInputStream(FileUpload.getExcelMouldFileSystemPath()

+ "caiwuduizhangdanchaxunjilu.xls");

HSSFWorkbook workbook = new HSSFWorkbook(is);

workbook = new  HSSFWorkbookUtil().writeWorkbookCWDZDCXJLList(workbook, returnList);

baos = new ByteArrayOutputStream();

try {

  workbook.write(baos);

} catch (IOException e) {

  e.printStackTrace();

}
byte[] ba = baos.toByteArray();

bais = new ByteArrayInputStream(ba);

return SUCCESS;

4.在HSSFWorkbookUtil类中添加

样式的方法

public static HSSFCellStyle[] getHSSFCellStyles(HSSFWorkbook workbook) {

List styleList = new ArrayList();

// 设置样式 // 正文样式(12号,宋体,水平居中,垂直居中)

HSSFCellStyle style = workbook.createCellStyle();

HSSFFont font = workbook.createFont();

font.setFontName("宋体");

font.setFontHeightInPoints((short) 12);

style.setFont(font);

style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

styleList.add(style);

设置样式 左对齐

HSSFCellStyle titleStyle = workbook.createCellStyle();

HSSFFont titleFont = workbook.createFont();

titleFont.setFontName("宋体");

titleFont.setFontHeightInPoints((short) 12);

titleStyle.setFont(titleFont);

titleStyle.setAlignment(HSSFCellStyle.ALIGN_LEFT);

titleStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

styleList.add(titleStyle);
}

写需要调取的方法

public HSSFWorkbook writeWorkbookCWDZDCXJLList(HSSFWorkbook workbook,

List list) {

>后面需要用到哪个样式直接调用就可以

HSSFCellStyle styles[] = this.getHSSFCellStyles(workbook);

HSSFSheet sheet = workbook.getSheet("Sheet1");

HSSFRow row = null;

HSSFCell cell = null;

// 封装表头

// row = sheet.getRow(0);

// row = sheet.getRow(1);

int rowNum = 1;

// 从第二行开始写数据

for (int i = 0; i < list.size(); i++) {

row = sheet.createRow(rowNum++);

Object[] obj = list.get(i);

for (int j = 0; j < obj.length; j++) {

if (obj[j] == null) {

obj[j] = "";

}

}

int lie = 0;

int index = 0;

// 序号

cell = row.createCell(lie++);

cell.setCellStyle(styles[1]);

cell.setCellValue(i + 1);

// 查询开始日期

cell = row.createCell(lie++);

cell.setCellStyle(styles[1]);

cell.setCellValue(obj[index++].toString());

}

return workbook;

}

5.Struts中的配置文件

你可能感兴趣的:(java如何导出表格)