java 实现execl导出 我应该怎么实现。希望是细致的说法,有完整的实例更好
阿神
阿神 2017-04-18 10:23:33
0
4
488

我现在要做一个execl的导出,所用的.jar我已经弄好了,现在我不知道要怎么实现这个功能,还请细致回答。不要凑数的评论。谢谢大家。
网上的例子都是 半截拉快的 实在不知从哪开始。

我点击按钮之后,到后台,然后怎么弄。。。excel里面的列名字都是自己根据需要写死的吗,还是怎么弄,需要展现的数据,是在先查 还是已经存在一个集合里面直接循环出来了,,,

阿神
阿神

闭关修行中......

membalas semua(4)
小葫芦

poiversi.

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.9</version>
</dependency>

Contoh Hello World

import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellUtil;

/**
 * @author Kevin Zou (kevinz@weghst.com)
 */
public class HelloWorld {

    public static void main(String[] args) throws Exception {
        Workbook workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet("HELLO");
        Map<String, Object> properties = new HashMap<>();

        // border around a cell
        properties.put(CellUtil.BORDER_TOP, CellStyle.BORDER_MEDIUM);
        properties.put(CellUtil.BORDER_BOTTOM, CellStyle.BORDER_MEDIUM);
        properties.put(CellUtil.BORDER_LEFT, CellStyle.BORDER_MEDIUM);
        properties.put(CellUtil.BORDER_RIGHT, CellStyle.BORDER_MEDIUM);
        // Give it a color (RED)
        properties.put(CellUtil.TOP_BORDER_COLOR, IndexedColors.RED.getIndex());
        properties.put(CellUtil.BOTTOM_BORDER_COLOR, IndexedColors.RED.getIndex());
        properties.put(CellUtil.LEFT_BORDER_COLOR, IndexedColors.RED.getIndex());
        properties.put(CellUtil.RIGHT_BORDER_COLOR, IndexedColors.RED.getIndex());

        // Apply the borders to the cell at B2
        Row row = sheet.createRow(1);
        Cell cell = row.createCell(1);

        for (Map.Entry<String, Object> e : properties.entrySet()) {
            CellUtil.setCellStyleProperty(cell, workbook, e.getKey(), e.getValue());
        }
        cell.setCellValue("First"); // 单元格值

        // Apply the borders to a 3x3 region starting at D4
        for (int ix = 3; ix <= 5; ix++) {
            row = sheet.createRow(ix);
            for (int iy = 3; iy <= 5; iy++) {
                cell = row.createCell(iy);
                for (Map.Entry<String, Object> e : properties.entrySet()) {
                    CellUtil.setCellStyleProperty(cell, workbook, e.getKey(), e.getValue());
                }

                cell.setCellValue(ix + " * " + iy); // 单元格值
            }
        }

        FileOutputStream fileOut = new FileOutputStream("C:/helloworld.xls");
        workbook.write(fileOut);
        fileOut.close();
        System.out.println("The end.");
    }
}

Panduan Ringkas poi

小葫芦

Gunakan sahaja jxl, terdapat banyak kes demo kes di Internet

Contohnya:

public void QueryExport(){
    //查询你需要的数据
    list = yourService.selectExportData(yourParams);
//封装成你需要的格式数据    
List<Map<String,String>> mlist = new ArrayList<Map<String,String>>();
    Iterator it = list.iterator();
    while(it.hasNext()){
        BABillProjectStatistics dp = (BABillProjectStatistics) it.next();
        Map<String,String> map = dp.toMap();
        mlist.add(map);
    }
    String fileName = "当前文件名称";
    String sheetName = "ExcelSheetName";
    //定义列头
    List<String> colList = new ArrayList<String>();
    colList.add("项目编号");
    //如果表列头为动态数据,直接按固定格式,封装在mlist中即可。
    JxlExcelUtils.exportexcle(httpServletResponse, fileName, mlist, sheetName, colList);
}

Kelas bantuan:

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import jxl.SheetSettings;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
  
/** 
 * jxl导出excel 
 * @author jamboree 
 * @date  2013-11-28 
 */  
public class JxlExcelUtils {

/** 
 * @author  
 * @param objData 导出内容数组 
 * @param sheetName 导出工作表的名称 
 * @param columns 导出Excel的表头数组 
 * @return 
 */  
public static int exportToExcel(HttpServletResponse response, List<Map<String, String>> objData, String sheetName,List<String> columns) {  
    int flag = 0;
    //声明工作簿jxl.write.WritableWorkbook  
    WritableWorkbook wwb;
    try {  
        //根据传进来的file对象创建可写入的Excel工作薄  
        OutputStream os = response.getOutputStream();
          
        wwb = Workbook.createWorkbook(os);

        /* 
         * 创建一个工作表、sheetName为工作表的名称、"0"为第一个工作表 
         * 打开Excel的时候会看到左下角默认有3个sheet、"sheet1、sheet2、sheet3"这样 
         * 代码中的"0"就是sheet1、其它的一一对应。 
         * createSheet(sheetName, 0)一个是工作表的名称,另一个是工作表在工作薄中的位置 
         */  
        WritableSheet ws = wwb.createSheet(sheetName, 0);
          
        SheetSettings ss = ws.getSettings();
        ss.setVerticalFreeze(1);//冻结表头  
        
        WritableFont font1 =new WritableFont(WritableFont.createFont("宋体"),11 ,WritableFont.BOLD);
        WritableFont font2 =new WritableFont(WritableFont.createFont("宋体"),11 ,WritableFont.NO_BOLD);
        WritableCellFormat wcf = new WritableCellFormat(font1);
        WritableCellFormat wcf2 = new WritableCellFormat(font2);
        WritableCellFormat wcf3 = new WritableCellFormat(font2);//设置样式,字体  

        //创建单元格样式  
        //WritableCellFormat wcf = new WritableCellFormat();

        //背景颜色  
        wcf.setBackground(jxl.format.Colour.LIGHT_GREEN);
        wcf.setAlignment(Alignment.CENTRE);//平行居中  
        wcf.setVerticalAlignment(VerticalAlignment.CENTRE);//垂直居中  
        wcf3.setAlignment(Alignment.CENTRE);//平行居中  
        wcf3.setVerticalAlignment(VerticalAlignment.CENTRE);//垂直居中  
        wcf3.setBackground(Colour.WHITE);
        wcf3.setBorder(Border.ALL, BorderLineStyle.THIN);
        wcf2.setAlignment(Alignment.CENTRE);//平行居中  
        wcf2.setVerticalAlignment(VerticalAlignment.CENTRE);//垂直居中  

        /* 
         * 这个是单元格内容居中显示 
         * 还有很多很多样式 
         */  
        wcf.setAlignment(Alignment.CENTRE);

        //判断一下表头数组是否有数据  
        if (columns != null && columns.size() > 0) {  

            //循环写入表头  
            for (int i = 0; i < columns.size(); i++) {  

                /* 
                 * 添加单元格(Cell)内容addCell() 
                 * 添加Label对象Label() 
                 * 数据的类型有很多种、在这里你需要什么类型就导入什么类型 
                 * 如:jxl.write.DateTime 、jxl.write.Number、jxl.write.Label 
                 * Label(i, 0, columns[i], wcf) 
                 * 其中i为列、0为行、columns[i]为数据、wcf为样式 
                 * 合起来就是说将columns[i]添加到第一行(行、列下标都是从0开始)第i列、样式为什么"色"内容居中 
                 */  
                ws.addCell(new Label(i, 0, columns.get(i), wcf));
            }  

            //判断表中是否有数据  
            if (objData != null && objData.size() > 0) {  
                //循环写入表中数据  
                for (int i = 0; i < objData.size(); i++) {  

                    //转换成map集合{activyName:测试功能,count:2}  
                    Map<String, String> map = (Map<String, String>)objData.get(i);

                    //循环输出map中的子集:既列值  
                    int j=0;
                    for(Object o:map.keySet()){  
                        //ps:因为要“”通用”“导出功能,所以这里循环的时候不是get("Name"),而是通过map.get(o)  
                        ws.addCell(new Label(j,i+1,String.valueOf(map.get(o)),wcf3));
                        j++;
                    }  
                }  
            }else{  
                flag = -1;
            }  

            //写入Exel工作表  
            wwb.write();

            //关闭Excel工作薄对象   
            wwb.close();
              
            //关闭流  
            os.flush();
            os.close();
              
            os =null;
        }  
    }catch (IllegalStateException e) {  
        System.err.println(e.getMessage());
    }  
    catch (Exception ex) {  
        flag = 0;
        ex.printStackTrace();
    }  

    return flag;
}  
/** 
 * 下载excel 
 * @author  
 * @param response 
 * @param filename 文件名 ,如:20110808.xls 
 * @param listData 数据源 
 * @param sheetName 表头名称 
 * @param columns 列名称集合,如:{物品名称,数量,单价} 
 */  
public static void exportexcle(HttpServletResponse response,String filename,List<Map<String, String>> listData,String sheetName,List<String> columns)  
{  
    //调用上面的方法、生成Excel文件  
    response.setContentType("application/vnd.ms-excel");
    //response.setHeader("Content-Disposition", "attachment;filename="+filename);
    try {  
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("gb2312"), "ISO8859-1") + ".xls");

        exportToExcel(response, listData, sheetName, columns);
    } catch (UnsupportedEncodingException e) {  
        e.printStackTrace();
    }   
}  

}

巴扎黑

Pengajaran langsung, cukup terperinci

Ty80

Saya sedang mengeksport melalui JS (Chrome), tetapi terdapat kelas alat yang menggunakan refleksi Java untuk mengeksport Excel, yang saya ingin kongsikan dengan subjek~

Pelaksanaan klasik eksport Java POI ke EXCEL Eksport Java ke Excel

Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!