Java-list<Object>形式客户端保存为excel文件

package com.HeiBeiEDU.test2;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JOptionPane;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class ListToExcel {

    /**
     *
     * @param name
     *            Excel保存的主题名
     * @param data
     *            里边有Map和List Map存放字段对应关系(ziDuan,字段的第一个字符是序号)
     *            List存放对象数据(listData)
     * @return [0]是fileName [1]是filePath
     */
    public static String[] objListToExcel(String name, Map data, String path) {
        Map<String, String> ziDuan = (Map<String, String>) data.get("ziDuan");
        List listData = (List) data.get("listData");
        Object[] keys = ziDuan.keySet().toArray();
        String[] ziDuanKeys = new String[keys.length];
        for (int k = 0; k < keys.length; k++) {
            String temp = keys[k].toString();
            int xuHao = Integer.valueOf(temp.substring(0, 1));
            ziDuanKeys[xuHao] = temp.substring(1);
        }
        try {
            File newFile = new File(path);

            if (newFile.exists()) {
                int ii = JOptionPane.showConfirmDialog(null, "文件已存在,你确定要覆盖吗?", "文件已存在", JOptionPane.YES_NO_OPTION);
                if (ii == 0) {// 确定
                    newFile.createNewFile();
                    System.out.println("创建文件成功:" + path);
                    HSSFWorkbook wb = new HSSFWorkbook();
                    HSSFSheet sheet = wb.createSheet();

                    for (int i = 0; i < listData.size(); i++) {
                        HSSFRow row = sheet.createRow(i);
                        Object obj = listData.get(i);
                        for (int j = 0; j < ziDuanKeys.length; j++) {
                            HSSFCell cell = row.createCell(j);
                            if (i == 0) {
                                sheet.setColumnWidth(j, 6000);
                                cell.setCellValue(new HSSFRichTextString(ziDuan.get(j + ziDuanKeys[j])));
                            } else {
                                String ziDuanName = (String) ziDuanKeys[j];
                                System.out.println(ziDuanName);
                                ziDuanName = ziDuanName.replaceFirst(ziDuanName.substring(0, 1),
                                        ziDuanName.substring(0, 1).toUpperCase());
                                ziDuanName = "get" + ziDuanName;
                                Class clazz = Class.forName(obj.getClass().getName());
                                Method[] methods = clazz.getMethods();
                                Pattern pattern = Pattern.compile(ziDuanName);
                                Matcher mat = null;
                                for (Method m : methods) {
                                    mat = pattern.matcher(m.getName());
                                    if (mat.find()) {
                                        Object shuXing = m.invoke(obj, null);
                                        if (shuXing != null) {
                                            cell.setCellValue(shuXing.toString());// 这里可以做数据格式处理
                                        } else {
                                            cell.setCellValue("");
                                        }
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    OutputStream out = new FileOutputStream(path);
                    wb.write(out);// 写入File
                    out.flush();
                    out.close();
                }
            } else {
                newFile.createNewFile();
                System.out.println("创建文件成功:" + path);
                HSSFWorkbook wb = new HSSFWorkbook();
                HSSFSheet sheet = wb.createSheet();

                for (int i = 0; i < listData.size(); i++) {
                    HSSFRow row = sheet.createRow(i);
                    Object obj = listData.get(i);
                    for (int j = 0; j < ziDuanKeys.length; j++) {
                        HSSFCell cell = row.createCell(j);
                        if (i == 0) {
                            sheet.setColumnWidth(j, 6000);
                            cell.setCellValue(new HSSFRichTextString(ziDuan.get(j + ziDuanKeys[j])));
                        } else {
                            String ziDuanName = (String) ziDuanKeys[j];
                            System.out.println(ziDuanName);
                            ziDuanName = ziDuanName.replaceFirst(ziDuanName.substring(0, 1),
                                    ziDuanName.substring(0, 1).toUpperCase());
                            ziDuanName = "get" + ziDuanName;
                            Class clazz = Class.forName(obj.getClass().getName());
                            Method[] methods = clazz.getMethods();
                            Pattern pattern = Pattern.compile(ziDuanName);
                            Matcher mat = null;
                            for (Method m : methods) {
                                mat = pattern.matcher(m.getName());
                                if (mat.find()) {
                                    Object shuXing = m.invoke(obj, null);
                                    if (shuXing != null) {
                                        cell.setCellValue(shuXing.toString());// 这里可以做数据格式处理
                                    } else {
                                        cell.setCellValue("");
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }
                OutputStream out = new FileOutputStream(path);
                wb.write(out);// 写入File
                out.flush();
                out.close();
            }

            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}

               测试代码为:

try {
                            List listData = new ArrayList();   //---------此处应遍历真正的list,但是现在没有办法测试webservice,所以先写测试代码-----------------------------
                            for (int i = 0; i < 6; i++) {
                                CheckPerson person = new CheckPerson();
                                person.setDHHM("145647583486");
                                person.setGMSFHM("13546876874786643");
                                person.setMZ("MZ");
                                person.setXM("XM");
                                person.setXZ("XZ");

                                listData.add(person);
                            }

                            Map<String, String> ziDuan = new HashMap<String, String>();
                            ziDuan.put("0DHHM", "电话号码");//属性前边的数字代表字段的先后顺序。
                            ziDuan.put("1MZ", "暂定");//最好将源码中判别顺序的格式改为"序号-字段"。
                            ziDuan.put("2XM", "姓名");
                            ziDuan.put("3XZ", "住址");
                            Map data = new HashMap();
                            data.put("listData", listData);
                            data.put("ziDuan", ziDuan);
                            ListToExcel.objListToExcel("爆破作业人员查询结果名单", data,path);
                     }catch(Exception e3){
                         e3.printStackTrace();
                     }
时间: 2024-08-03 16:06:51

Java-list<Object>形式客户端保存为excel文件的相关文章

[SAP ABAP开发技术总结]客户端文本文件、Excel文件上传下载

目录导航 声明:原创作品,转载时请注明文章来自SAP师太博客,并以超链接形式标明文章原始出处,否则将追究法律责任!原文出自: 客户端文本文件或Excel文件导入与导出... 1 TEXT_CONVERT_XLS_TO_SAP. 1 ALSM_EXCEL_TO_INTERNAL_TABLE. 3 SAP_CONVERT_TO_XLS_FORMAT. 5 客户端文本文件或Excel文件导入与导出 TEXT_CONVERT_XLS_TO_SAP TEXT_CONVERT_XLS_TO_SAP函数可以将

Java web中不同浏览器间导出Excel文件名称乱码问题解决方案

问题描述: 对于不同浏览器存在对中文编码格式问题,从而在导出Excel文件时,中文文件名出现乱码的情况,即在程序中给要导出的文件指定一个中文名字时,在浏览器上出现的下载框中的文件名出现了乱码,解决如下: 解决方案: [java] view plain copy Date dt=new Date();//如果不需要格式,可直接用dt,dt就是当前系统时间 DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");//设置显示格

java导出大批量(百万以上)数据的excel文件

1.传统的导出方式会消耗大量的内存,2003每个sheet页最多65536条数据,2007每个sheet页可以达到100万条数据以上,2007会在生成Workbook时清理数据,所以2007导出量更大; 2.可以导出多个excel文件到某个目录中,然后打包下载; 3.导出excel格式的xml文件,这种方式可以分批导出数据,适用于大批量数据的导出,以下简单介绍这种方式: 代码如下: 1 package com.epay.utils; 2 3 /** 4 * 大数据量导出成EXCEL或XML 5

死机,断电,Excel未来得及保存?Excel文件恢复来帮你!

Excel自动恢复功能只能将工作簿恢复到最后一次自动保存时的状态,而不能完全恢复工作簿.不过相对于不能恢复,不能完全恢复大家还是可以接收的吧. 当Excel文件因为电脑突然断电或死机未来得及保存时,在开机后打开工作簿时会自动出现"文档恢复"任务窗口.出现的时候一定要注意哦,不要关闭文档,不然就真的没法恢复了. 恢复文件的步骤如下 1.在"文档恢复"任务窗格的"可用文件"列表框中单击最近保存的文件,即可恢复之前未保存的文档.如果"可用文件

java poi 读取有密码加密的Excel文件

String excelPath = "Excel文件路徑"; String password = "Excel文件密碼"; Workbook workbook; InputStream inp = new FileInputStream(excelPath); //解密 POIFSFileSystem pfs = new POIFSFileSystem(inp); inp.close(); EncryptionInfo encInfo = new Encrypti

下载GridView(保存为Excel文件)

aspx页面前台:(使用用户控件) <uc1:DownExcel ID="DownExcel1" runat="server" /> aspx页面后台: protected void Page_Load(object sender, EventArgs e)    {                  DownExcel1.myEvent += new EventHandler(BindGV);            DownExcel1.sFileNa

将matlab数据保存为excel文件

摘录网址:https://blog.csdn.net/wangh0802/article/details/70312415 参考网址:https://jingyan.baidu.com/article/b2c186c83ec146c46ef6ff99.html 读取: A = xlsread('Excel路径+Excel的名称','工作表名称') 例子: A = xlsread('创新班.xlsx','Sheet2') A = xlsread('创新班.xlsx','Sheet2','a1:c1

matlab数据保存为excel文件

摘录网址:https://blog.csdn.net/wangh0802/article/details/70312415 参考网址:https://jingyan.baidu.com/article/b2c186c83ec146c46ef6ff99.html 读取: A = xlsread('Excel路径+Excel的名称','工作表名称') 例子: A = xlsread('创新班.xlsx','Sheet2') A = xlsread('创新班.xlsx','Sheet2','a1:c1

NPOI 2.0 读取、编辑、保存Excel文件

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; namespace ReadExcel { class Program { static void Main(string[] args) { //要操作的excel文件路径 string