首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > Java Web开发 >

导出动态EXCEL 求不简单人士指导 !

2013-12-07 
导出动态EXCEL 求牛逼人士指导 !!!!!!!我现在的需求是生成这样一个EXCEL 这些内容都是动态的名字可能有多

导出动态EXCEL 求牛逼人士指导 !!!!!!!

我现在的需求是生成这样一个EXCEL 这些内容都是动态的  名字可能有多个  类别(也就是那个一列) 也可能是多个  我还有填充 名称和类别的值  一个类别 和一个名字 确定一个值 

不知道 我这样 大家懂不懂  急需 帮忙啊!!!导出动态EXCEL 求不简单人士指导 ! EXCEL
[解决办法]
让excel存成csv的格式的 windows平台用 jacob linux用poi
[解决办法]
百度搜索 java导出excel 有的是代码 粘进去就行
[解决办法]
就是循环索引 excel 的单元格。
[解决办法]
JAVA
POI

详见链接: http://blog.csdn.net/whx405831799/article/details/7750287
[解决办法]
用poi好了,还有扛物品。。。
[解决办法]
网上有专门处理excel的jar包的,excel中的行列对应的就是二维数组的感觉,
[解决办法]
往里面放数据也难?
[解决办法]
希望有用,以前写的一个读写excel的工具对象,支持不同excel版本

import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
import jodd.typeconverter.Convert;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 解析电子表格,支持excel2007和excel2007以前的版本
 * User: liuzhaoyang
 * Date: 13-6-20
 * Time: 下午6:15
 */
public class AnalyseExcel {
    private static Logger logger = Logger.getLogger(AnalyseExcel.class);

    /**
     * 读取电子表格内容,支持2007版本和2007之前的版本
     * Author:liuzhaoyang
     * Date:2013-06-20
     *
     * @param file
     */
    public List<List<Object>> readExcel(File file) {
        InputStream inputStream = null;
        try {
            String fileExtension = Files.getFileExtension(file.getPath());
            logger.debug("fileExtension is: " + fileExtension);
            inputStream = org.apache.commons.io.FileUtils.openInputStream(file);

            List<List<Object>> listExcel = readExcel(inputStream, fileExtension);
            logger.debug(Objects.toStringHelper("").add("listExcel", listExcel));

            return listExcel;

        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            throw Throwables.propagate(e);
        } finally {
            IOUtils.closeQuietly(inputStream);    //关闭文件流
        }
    }

    public List<List<Object>> readExcel(InputStream inputStream, String fileExtension) {
        try {
            Workbook workbook = workbookType(fileExtension, inputStream);
            Preconditions.checkNotNull(workbook, "workbook 对象 is %s", workbook);   //如果workbook对象为null,抛出异常,不往下执行



            Sheet xssfSheet = workbook.getSheetAt(0);   //获取第一个sheet,当然,可以判断有几个sheet,进行遍历分析
            Iterator<Row> iterator = xssfSheet.iterator();   //获取表格行 row

            List<List<Object>> listExcel = Lists.newArrayList();  //声明一个List对象 ,保存表格行(row)信息
            while (iterator.hasNext()) {
                List<Object> listRow = Lists.newArrayList();    //声明一个List对象,保存列(cell)信息
                Row row = iterator.next();
                Iterator<Cell> cellIterator = row.cellIterator();    //遍历行(row),获取列(cell)
                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    if (Objects.equal(cell.getCellType(), Cell.CELL_TYPE_STRING)) {  //如果列(cell)是String类型,按照取String方式取数据
                        listRow.add(cell.getStringCellValue());  //将列数据存入 listRow 中
                    }
                    if (Objects.equal(cell.getCellType(), Cell.CELL_TYPE_NUMERIC)) {  //如果列是Number类型,按照Number取数据,但是这里不支持int类型
                        listRow.add(cell.getNumericCellValue());
                    }
                }
                listExcel.add(listRow);    //将行对象(listRow)存入listExcel对象中
            }

            return listExcel;

        } finally {
            IOUtils.closeQuietly(inputStream);    //关闭文件流
        }
    }

    /**
     * 向excel2007或以上版本中写数据
     * Author:liuzhaoyang
     * Date:2013-06-26
     *
     * @param listResult 数据集
     * @return inputSteam 文件输出流
     */
    public byte[] writeExcelForXlsx(List<Map<String, Object>> listResult) {
        byte[] bytesExcel = writeExcel(listResult, "xlsx");
        return bytesExcel;
    }

    /**
     * 向excel2003或以下版本中写数据
     * Author:liuzhaoyang
     * Date:2013-06-26
     *
     * @param listResult 数据集
     * @return inputSteam 文件输出流
     */
    public byte[] writeExcelForXls(List<Map<String, Object>> listResult) {
        byte[] bytesExcel = writeExcel(listResult, "xls");
        return bytesExcel;
    }

    public byte[] writeExcel(List<Map<String, Object>> listResult, String excelVersion) {

        byte[] bytesExcel;

        Workbook workbook = null;
        if (Objects.equal(excelVersion, "xlsx")) {
            workbook = new XSSFWorkbook();
        }
        if (Objects.equal(excelVersion, "xls")) {
            workbook = new HSSFWorkbook();
        }


        Sheet sheet = workbook.createSheet("sheet1");

        int i = 0;
        for (Map<String, Object> mapCell : listResult) {
            Row row = sheet.createRow(i++);
            //            MapUtils.debugPrint(System.out, ">>>", mapCell);
            int j = 0;
            for (String key : mapCell.keySet()) {
                Object objCellValue = MapUtils.getObject(mapCell, key);
                String objType = objCellValue.getClass().getSimpleName();
                if (Objects.equal(objType, "String")) {
                    row.createCell(j++).setCellValue(objCellValue.toString());
                } else {
                    row.createCell(j++).setCellValue(Convert.toDouble(objCellValue));
                }
                //                row.createCell(0).setCellValue(objCellValue);
            }
        }

        OutputStream outputStream;
        File file = new File("temp." + excelVersion);
        try {
            outputStream = org.apache.commons.io.FileUtils.openOutputStream(file);
            workbook.write(outputStream);
            bytesExcel = Files.toByteArray(file);
//            Files.write(bytesExcel, new File("d://cxxzc." + excelVersion));
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            throw Throwables.propagate(e);
        }
        return bytesExcel;
    }

    /**
     * 根据不同的扩展名(2007版本和2003版本的扩展名不同),进行不同的处理
     * Author:liuzhaoyang
     * Date:2013-06-20
     *
     * @param extension   扩展名
     * @param inputStream 输入流
     * @return Workbook
     */
    private Workbook workbookType(String extension, InputStream inputStream) {
        if (Objects.equal(extension, "xlsx")) {
            try {
                return new XSSFWorkbook(inputStream);
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
                throw Throwables.propagate(e);
            }
        }
        if (Objects.equal(extension, "xls")) {
            try {
                return new HSSFWorkbook(inputStream);
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
                throw Throwables.propagate(e);
            }


        }
        return null;
    }


}

[解决办法]
用jxl 下面是我读取合并单元格情况第一二列
package com.shunan.excel;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import jxl.Range;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

/**
 * @author Cooly 2013-9-26
 * StandartExcelHandle.java 读取标准
 * Copyright (c) 2013 by SAKJ.
 * @version 1.0
 */
public class StandartExcelHandle extends ExcelHandle {

private List<String[]> examCategoryLists;//标准化大类(A级要素)
private List<String[]> examItemLists;//标准化项目(B级要素)
private Sheet sheet;//excel表单

public StandartExcelHandle(String fileName) {
try {
Workbook wb = Workbook.getWorkbook(new File(fileName));
sheet = wb.getSheet(0);
Range[] randges = sheet.getMergedCells();//读取所有的合并单元格
readExamCategory(randges);//读取所有的类目
readExamItem(randges);//读取所有的项目

} catch (BiffException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
/**读取excel每行记录
 * @return excel记录
 */
@Override
public  List<StandardVo> readWorkBook() {
List<StandardVo> vos = new ArrayList<StandardVo>();
int rows = sheet.getRows();//excel所有行
String examCategory = null;//类目名称
String examItem = null;//项目名称

for(int i=1;i<rows;i++){//从第2行开始
StandardVo vo = new StandardVo();
//判断处该记录所属类目
examCategory = sheet.getCell(0, i).getContents();
if(examCategory==null
[解决办法]
examCategory.trim().length()==0){//类目是否跨行
for(int j=0,len=examCategoryLists.size();j<len;j++){
String[] _category= examCategoryLists.get(j);
if(i>=Integer.parseInt(_category[0])&&i<=Integer.parseInt(_category[1])){
examCategory = _category[2];//赋值给类目名称
//System.out.println("examCategory:"+examCategory);
break;
}
}
}


//判断处该记录所属项目
examItem = sheet.getCell(1, i).getContents();
if(examItem==null
[解决办法]
examItem.trim().length()==0){//项目是否跨列
for(int x=0,len=examItemLists.size();x<len;x++){
String[] _examItem= examItemLists.get(x);
if(i>=Integer.parseInt(_examItem[0])&&i<=Integer.parseInt(_examItem[1])){
examItem = _examItem[2];//复制给项目名称
//System.out.println("examItem:"+examItem);
break;
}
}
}

//System.out.println("examItem:"+examItem);
vo.setExamCategory(examCategory);//考评类目
vo.setExamItem(examItem);//考评项目
vo.setExamItemContent(sheet.getCell(2, i).getContents());//考评内容
vo.setExamItemScore(sheet.getCell(3, i).getContents());//标准分值
vo.setExamItemMethod(sheet.getCell(4, i).getContents());//考评办法
vos.add(vo);

}
//销毁资源
//distory();
return vos;
}


/**读取excel每行记录,同时写入标准文件里
 * @return excel记录
 */
@Override
public List<StandardVo> readWorkBook(String standardName,String outFileName) {
List<StandardVo> vos = readWorkBook();
try {
String fileName = outFileName.substring(0,outFileName.indexOf("."))+".xls";
OutputStream os = new FileOutputStream(fileName);// 输出的Excel文件URL
WritableWorkbook wwb = Workbook.createWorkbook(os);// 创建可写工作薄
WritableSheet ws = wwb.createSheet(standardName, 0);// 创建可写工作表

//标准化类别标题
WritableFont wf = new WritableFont(WritableFont.TIMES, 16,
WritableFont.BOLD, false);// 设置写入字体
WritableCellFormat wcfF = new WritableCellFormat(wf);// 设置CellFormat
wcfF.setAlignment(jxl.format.Alignment.CENTRE);//水平居中
Label labelCF1 = new Label(3, 0, standardName, wcfF);// 创建写入位置,内容和格式
ws.addCell(labelCF1);// 将Label写入sheet中

//标准化字段名称

wf = new WritableFont(WritableFont.TIMES, 14,
WritableFont.BOLD, false);// 设置写入字体
wcfF = new WritableCellFormat(wf);// 设置CellFormat
ws.addCell(new Label(0, 1, "考评类目", wcfF));
ws.addCell(new Label(1, 1, "考评项目", wcfF));
ws.addCell(new Label(2, 1, "考评内容", wcfF));


ws.addCell(new Label(3, 1, "考评分值", wcfF));
ws.addCell(new Label(4, 1, "考评办法", wcfF));

//写入数据
wf = new WritableFont(WritableFont.TIMES, 12,
WritableFont.NO_BOLD, false);// 设置写入字体
wcfF = new WritableCellFormat(wf);// 设置CellFormat
wcfF.setWrap(true);
wcfF.setAlignment(jxl.format.Alignment.LEFT);//水平居中
wcfF.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
int row = 2;
int rows = vos.size()+2;
for(int j=0;row<rows;row++,j++){
ws.setRowView(row, 1000);
ws.setColumnView(0, 30);
ws.setColumnView(1, 30);
ws.setColumnView(2, 30);
ws.setColumnView(3, 15);
ws.setColumnView(4, 100);
StandardVo vo = vos.get(j);
ws.addCell(new Label(0, row, vo.getExamCategory(),wcfF));
ws.addCell(new Label(1, row, vo.getExamItem(),wcfF));
ws.addCell(new Label(2, row, vo.getExamItemContent(),wcfF));
ws.addCell(new Label(3, row, vo.getExamItemScore(),wcfF));
ws.addCell(new Label(4, row, vo.getExamItemMethod(),wcfF));

}

// 现在可以写了
wwb.write();
// 写完后关闭
wwb.close();
// 输出流也关闭吧
os.close();

} catch (Exception e) {
System.out.println(e);
}
System.out.println("ok");
return vos;
}

/**
 * 读取第一列合并的单元格类目
 * @param range 合并了单元格单元格类目数组
 * @return
 */
private void readExamCategory(Range[] ranges){
examCategoryLists = new ArrayList<String[]>();
for(int i=0,len=ranges.length;i<len;i++){
String[] str = readMergeRanges(ranges[i],0);//第一列合并的单元格类目
if(str!=null){
System.out.println("起始行:"+str[0]+"-结束行:"+str[1]+"-类目:"+str[2]);
examCategoryLists.add(str);
}

}

}
/**
 * 读取第二列合并的单元格项目目
 * @param range 合并了单元格单元格类目数组
 * @return
 */
private void readExamItem(Range[] ranges){
examItemLists = new ArrayList<String[]>();
for(int i=0,len=ranges.length;i<len;i++){
String[] str = readMergeRanges(ranges[i],1);//第二列合并的单元格项目
if(str!=null){
System.out.println("起始行:"+str[0]+"-结束行:"+str[1]+"-项目:"+str[2]);
examItemLists.add(str);
}
}
}


/**
 * 返回合并单元格开始行,结束行,该条目名称
 * @param range 合并了单元格类目或者项目
 * @param column 0或者1列
 * @return String[0] -开始行 String[1] -结束行 String[2] -条目名称
 */
private String[] readMergeRanges(Range range,int column){
String[] map = null;
//System.out.println("-除了第一列或者第二列,有合并单元格则抛出异常--"++":"+range.getTopLeft().getColumn()+":"+range.getTopLeft().getContents());
//除了第一列或者第二列,有合并单元格则抛出异常
if(range.getTopLeft().getColumn()>=2
[解决办法]
range.getBottomRight().getColumn()>=2){
throw new IllegalArgumentException("不是标准excel格式(除了第一列或者第二列,不能有合并单元格),第"+(range.getTopLeft().getRow()+1)+"行"+"第"+(columnLabels[range.getTopLeft().getColumn()])+"列有合并现象,请检查!!!");
}
if(range.getTopLeft().getColumn()==column&&range.getBottomRight().getColumn()==column){//第一列或者第二列
map = new String[3];
int[] rows = new int[2];
 rows[0] = range.getTopLeft().getRow();//开始行
 rows[1] = range.getBottomRight().getRow();//结束行
 map[0] = String.valueOf(rows[0]);
 map[1] = String.valueOf(rows[1]);
 map[2] = range.getTopLeft().getContents();//条目名称
}

return map;
}


//销毁资源
private void distory(){
examCategoryLists = null;
examItemLists = null;
//sheet = null;
}
public static void main(String[] args) {
StandartExcelHandle se =new StandartExcelHandle("D:\\works\\quanxian\\src\\com\\shunan\\excel\\Book1.xls");
List<StandardVo> vos = se.readWorkBook();
System.out.println("=====================================================");
for(int j=0,len=vos.size();j<len;j++){
StandardVo vo = vos.get(j);
System.out.print(vo.getExamCategory());
System.out.print(vo.getExamItem());
System.out.print(vo.getExamItemContent());
System.out.print(vo.getExamItemMethod());
System.out.print(vo.getExamItemScore());
System.out.println();
System.out.println("--------------------------------");
}
se.readWorkBook("白酒生产企业安全生产标准化评定标准1", "D:\\works\\quanxian\\src\\com\\shunan\\excel\\白酒生产企业安全生产标准化评定标准1.xls");
}

}

[解决办法]
spring架构可以直接生成excel
[解决办法]


public ExcelModel createDownLoadExcel(List list,
            ExcelModel excel) throws Exception {
        String titleStr = "考生编号;考生姓名;";


        ArrayList data = new ArrayList();        
        Iterator ir = list.iterator();
        while(ir.hasNext()){
            ArrayList rowData = new ArrayList();
            User user = (User)ir.next();
            rowData.add(user.getUid());
            rowData.add(user.getName());
            data.add(rowData);        
        }
        
    
        String[] titles = titleStr.split(";");
        ArrayList header = new ArrayList();
        for (int i=0;i<titles.length;i++){
            header.add(titles[i]);
        }
        //设置报表标题
        excel.setHeader(header);
        //设置报表内容
        excel.setData(data);
        return excel;
    }


String titleStr = "考生编号;考生姓名;";这个列可以随便加,以;号分割
[解决办法]
一个两层的遍历,还好吧

热点排行