java导出excel:
- import java.io.ByteArrayOutputStream;
- import java.io.File;
- import java.io.IOException;
- import java.text.DateFormat;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import java.util.Vector;
- import javax.servlet.ServletOutputStream;
- import jxl.Workbook;
- import jxl.format.Colour;
- import jxl.format.UnderlineStyle;
- import jxl.write.Label;
- import jxl.write.WritableCellFormat;
- import jxl.write.WritableFont;
- import jxl.write.WritableSheet;
- import jxl.write.WritableWorkbook;
- import jxl.write.WriteException;
- public class ExcelBean {
- public ExcelBean() {
- }
- public void exportToExcel(String tempFilePath, String filename,
- String sheetname, String[] titles, Vector vect,ServletOutputStream outputStream) throws Exception {
- try {
- Workbook wb = Workbook.getWorkbook(new File(tempFilePath));
- ByteArrayOutputStream targetFile = new ByteArrayOutputStream();
- // 创建新的Excel 工作簿
- WritableWorkbook workbook = Workbook.createWorkbook(targetFile, wb);
- // 在Excel工作簿中建一工作表,其名为:第一页
- WritableSheet wsheet = workbook.createSheet(sheetname, 0); // sheet();
- WritableFont font = new WritableFont(WritableFont.ARIAL, 14,
- WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE,
- Colour.BLACK);
- WritableCellFormat format = new WritableCellFormat(font);
- for (int i = 0; i < titles.length; i++) {
- Label wlabel1 = new Label(i, 0, titles[i], format); // 行、列、单元格中的文本、文本格式
- wsheet.addCell(wlabel1);
- }
- font = new WritableFont(WritableFont.createFont("宋体"), 12,
- WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE,
- Colour.BLACK);
- format = new WritableCellFormat(font);
- for (int i = 1; i < vect.size() + 1; i++) { // 在索引0的位置创建行(最顶端的行)
- Object[] sdata = (Object[]) vect.elementAt(i - 1);
- for (int j = 0; j < sdata.length; j++) { // 在索引0的位置创建单元格(左上端)
- Label wlabel1 = new Label(j, i, (String) sdata[j], format); // 行、列、单元格中的文本、文本格式
- wsheet.addCell(wlabel1);
- }
- }
- workbook.write();
- workbook.close();
- wb.close();
- targetFile.writeTo(outputStream);
- targetFile.close();
- } catch (WriteException ex1) {
- System.out.println("WriteException:" + ex1.getMessage());
- } catch (IOException ex2) {
- System.out.println("IOException:" + ex2.getMessage());
- }
- }
- public static String compare_date(String DATE1, String DATE2) {
- DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
- try {
- Date dt1 = df.parse(DATE1);
- Date dt2 = df.parse(DATE2);
- if (dt1.getTime() > dt2.getTime()) {
- return "1";
- } else if (dt1.getTime() < dt2.getTime()) {
- return "-1";
- } else {
- return "0";
- }
- } catch (Exception exception) {
- exception.printStackTrace();
- }
- return "0";
- }
- }