java批量生成excel代码分享

package com.test.util;

/** 
 * @author ocq
 * 
 */
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

public class SimpleExcelWrite {
    public static void createExcel(OutputStream os, String[] headField, String[] values) throws WriteException,
            IOException {
        // 创建工作薄
        WritableWorkbook workbook = Workbook.createWorkbook(os);
        // 创建新的一页
        WritableSheet sheet = workbook.createSheet("First Sheet", 0);

        // 创建要显示的内容,创建一个单元格,第一个参数为列坐标,第二个参数为行坐标,第三个参数为内容
        for (int y = 0; y < 100 * 100 + 1; y++) {
            int index = y % 100;
            if (index == 0) {
                for (int x = 0; x < headField.length; x++) {
                    Label xuexiao = new Label(x, index, headField[x]);
                    sheet.addCell(xuexiao);
                }
            } else {
                for (int x = 0; x < values.length; x++) {
                    String string = values[x];
                    if (x == 0 || x == 3) {
                        string += y;
                    }
                    Label xuexiao = new Label(x, index, string);
                    sheet.addCell(xuexiao);
                }
            }

        }
        // 把创建的内容写入到输出流中,并关闭输出流
        workbook.write();
        workbook.close();
        os.close();
    }

    public static void main(String[] args) throws WriteException, IOException {
        // List<String> headField=new ArrayList<String>();
        String[] headField = new String[] { "表头一", "表头2", ..... };

        String[] values = new String[] { "内容一", "内容2", ... };

        for (int i = 1; i < 101; i++) {
            OutputStream os = new FileOutputStream("file name" + i + ".xls");
            createExcel(os, headField, values);
        }

    }
}

需要引入jar包:www.andykhan.com/jexcelapi/download.html

复制下来查看效果吧

参考:Java生成和操作Excel文件

你可能感兴趣的:(java批量生成excel代码分享)