列表如何使用 Apache poi 将映射值写入 Excel 文件

2023-12-06

我得到列表哈希映射键和值,例如:{1=[ACSS Description1, ACSS Description2, ACSS Description3, SACSS Description4], 2=[11, 1, 4, 12]}

我想这样设置 Excel 单元格值:

ACSS Description1      11
ACSS Description2      1
ACSS Description3      4
ACSS Description4      12

但我得到这样的写入 excel 文件结果:

     empty                 11
     empty                  1
     empty                  4
     empty                 12

但我的示例代码片段始终显示第二列值,首先 列值显示空列。请让我知道我在哪里 搞错了?谢谢 。

  public  void  listhashMapValues(Map<Integer,List<String>> hashmap,List<Export>list){

    List<String> listpropertvalue =new ArrayList<String>();

    for(int i=0;i<list.size();i++){  //example size is 5

    String strValue=list.get(i).getDescription();

    System.out.println(strValue);
    listpropertvalue.add(strValue);
    hashmap.put(1, listpropertvalue); 
    }
    listpropertvalue =new ArrayList<String>();

    for(int i=0;i<list.size();i++){

    String strInterValue=list.get(i).getExportIntervalId().toString();

    listpropertvalue.add(strInterValue);
    hashmap.put(2, listpropertvalue); 
    }
    int rownum =1;
    int cellnum = 0;
    for(int i=0;i<hashmap.size();i++){

    List<Integer> listMap =new ArrayList<Integer>(hashmap.keySet());

    Integer key = listMap.get(i);

    List<String> nameList = hashmap.get(key);

     for(Object obj : nameList){

     rowtitle =worksheet.createRow(rownum++); 

    celltitle =rowtitle.createCell(cellnum); 

    if (obj instanceof String){

    celltitle =rowtitle.createCell(cellnum);

    celltitle.setCellValue((String) obj);
    }
    }
}
cellnum++;
rownum=1;
}
}

我的 pojo 类如下:

@Entity

@Table(name ="T_KPI_AUTO_EXPORT_CONFIG")

public class ExportReport implements Serializable  {

private String description;

private Integer exportIntervalId;

@Column(name ="Export_Interval_Id", nullable = false)

    public Integer getExportIntervalId() {

        return exportIntervalId;
    }
    public void setExportIntervalId(Integer exportIntervalId) {

        this.exportIntervalId = exportIntervalId;
    }
    @Column(name ="Description", nullable = false)

    public String getDescription() {

        return description;
    }
    public void setDescription(String description) {

        this.description = description;
    }
}

我创建一个类,其中包含可以帮助您执行以下操作的方法:

把你的数据从Criteria criteria=hibernateTemplate.getSessionFactory().openSession().createCriteria(ExportReport.‌​class); List<ExportReport> list = criteria.list();到地图

创建一个 Xlsx 文件并使用从地图写入数据所需的行数和单元格数对其进行初始化。

将地图中的数据写入 Xlsx 文件

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


public class UtilsMethod {

    private XSSFWorkbook workbook = new XSSFWorkbook();

    /*
     * Take a Map of integer and List of string and
     *Create a Xlsx file on given path with number of row equal to size of nameList And number of Cell equal to keyset size
     */
    public void initializeExcelFile(Map<Integer,List<String>>hashmap,String path) throws IOException{

        FileOutputStream out = new FileOutputStream( new File(path));
        Set<Integer> keyset = hashmap.keySet();
        XSSFSheet sheet = workbook.createSheet();
        XSSFRow row = null;
        List<String> nameList = hashmap.get(keyset.toArray()[0]);

        for(int j=1; j<nameList.size()+1;j++){
            row = sheet.createRow(j);
            if(null != row){
                for(int i=0;i<keyset.size();i++){
                    row.createCell(i);
                }
            }
        }

        workbook.write(out);
        out.close();
    }

    /*
     * Use initializeExcelFile(hashmap,path) to initialize a Xlsx file in given path 
     * After that, write the  content of hashmap into Xlsx file
     */
    public void writeToExcelfile(Map<Integer,List<String>>hashmap,String path) throws IOException{

        Set<Integer> keyset = hashmap.keySet();
        InputStream inp = new FileInputStream( new File(path));
        FileOutputStream out = new FileOutputStream( new File(path));
        int rownum = 1;
        int cellnum = 0;

        initializeExcelFile(hashmap,path);

        workbook = new XSSFWorkbook(inp);

        XSSFSheet sheet = workbook.getSheetAt(0);

        for(Integer key : keyset){
            List<String> nameList = hashmap.get(key);
            for(String s : nameList){
                XSSFRow row = sheet.getRow(rownum++);
                Cell cell = row.getCell(cellnum);
                if(null!=cell){
                    cell.setCellValue(s);
                }
            }
            cellnum++;
            rownum=1;
        }

        workbook.write(out);
        out.close();
        inp.close();
    }

    public Map<Integer,List<String>> putListIntoMap(List<ExportReport>exportReports) {

        Map<Integer,List<String>> exportRep = new TreeMap<Integer, List<String>>();
        List<String> descriptions = new ArrayList<String>();
        List<String> exportIntervalIds = new ArrayList<String>();

        for(ExportReport report:exportReports){
            descriptions.add(report.getDescription());
            exportIntervalIds.add(report.getExportIntervalId().toString());
        }

        exportRep.put(1, descriptions);
        exportRep.put(2, exportIntervalIds);

        return exportRep;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }

}

并测试类来测试所有 UtilsMethod 类的方法

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class Test {


    public static void main(String[] args) throws IOException {

        ExportReport exportReport = new ExportReport();
        exportReport.setExportIntervalId(11);
        exportReport.setDescription("ACCSDESCRIPTION1");

        ExportReport exportReport2 = new ExportReport();
        exportReport2.setExportIntervalId(1);
        exportReport2.setDescription("ACCSDESCRIPTION2");

        ExportReport exportReport3 = new ExportReport();
        exportReport3.setExportIntervalId(4);
        exportReport3.setDescription("ACCSDESCRIPTION3");

        ExportReport exportReport4 = new ExportReport();
        exportReport4.setExportIntervalId(12);
        exportReport4.setDescription("ACCSDESCRIPTION4");

        List<ExportReport> exportReports = new ArrayList<ExportReport>();

        exportReports.add(exportReport);
        exportReports.add(exportReport2);
        exportReports.add(exportReport3);
        exportReports.add(exportReport4);

        UtilsMethod utilsMethod = new UtilsMethod();

        Map<Integer,List<String>> map = utilsMethod.putListIntoMap(exportReports);
        System.out.println(map);


        utilsMethod.writeToExcelfile(map, "Writesheet.xlsx");

        System.out.println("Writesheet.xlsx written successfully" );

    }

}

运行Test类后,你将得到这个Xlsx文件

enter image description here

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

列表如何使用 Apache poi 将映射值写入 Excel 文件 的相关文章

  • Android 中的列表(特别是 RecyclerView 和 CardView)如何工作

    请原谅我问这个问题 但我是 Android 开发新手 尽管我正在尝试了解developer android com 网站上的基础知识 但大多数示例 即使他们说它们是为 Android Studio 构建的 尚未设置为使用 Gradle 因此
  • 如何强制jar使用(或jar运行的jvm)utf-8而不是系统的默认编码

    我的Windows默认编码是GBK 而我的Eclipse完全是utf 8编码 因此 在我的 Eclipse 中运行良好的应用程序崩溃了 因为导出为 jar 文件时这些单词变得不可读 我必须在 bat 文件中写入以下行才能运行该应用程序 st
  • Base36 编码字符串?

    我一直在网上查找 但找不到解决此问题的方法 在 Python Ruby 或 Java 中 如何对以下字符串进行 Base 36 编码 nOrG9Eh0uyeilM8Nnu5pTywj3935kW 5 Ruby 以 36 为基数 s unpa
  • 如何使用 JAVA 代码以编程方式捕获线程转储?

    我想通过 java 代码生成线程转储 我尝试使用 ThreadMXBean 为此 但我没有以正确的格式获得线程转储 因为我们正在使用jstack命令 请任何人提供一些帮助 他们是否有其他方式获取线程转储 使用任何其他 API 我想要的线程转
  • 从 MS Access 中提取 OLE 对象(Word 文档)

    我有一个 Microsoft Access 数据库 其中包含一个包含 Microsoft Word 文档的 OLE 对象字段 我试图找到代码来检索保存在 OLE 对象中的文件 以便用户可以从我的 JavaFx 应用程序中的按钮下载它 但没有
  • php隐藏所有错误[重复]

    这个问题在这里已经有答案了 隐藏的最佳做法是什么allPHP 错误 因为我不想向用户显示错误 我尝试过使用 htacess通过输入代码php flag display errors off在那里 但它返回给我一个500 error 还有其他
  • 为自定义驱动程序创建 GraphicsDevice

    我正在开发一个在嵌入式系统中使用 Java 的项目 我有用于屏幕和触摸输入的驱动程序 以及用于文本输入的虚拟键盘 我的屏幕驱动程序有一个Graphics2D您可以绘制的对象和repaint Rectangle 更新方法 类似地 触摸驱动器能
  • 为什么 MOVE CURSOR 在 OS X Mountain Lion 上不显示?

    我正在做一个项目 想看看 Swing 提供的每个光标是什么样子的 public class Test public static void main String args JFrame frame new JFrame frame set
  • 从休眠乐观锁定异常中恢复

    我有一个这样的方法 Transactional propagation Propagation REQUIRES NEW public void doSomeWork Entity entity dao loadEntity do some
  • 添加到列表时有没有办法避免循环?

    我想知道这样的代码 List
  • Spring Data JPA:查询如何返回非实体对象或对象列表?

    我在我的项目中使用 Spring Data JPA 我正在演奏数百万张唱片 我有一个要求 我必须获取各种表的数据并构建一个对象 然后将其绘制在 UI 上 现在如何实现我的 Spring 数据存储库 我读到它可以通过命名本机查询来实现 如果指
  • 我们如何测试包私有类?

    我正在看书Effective Java in Item 13 Minimize the accessibility of classes and members 它提到 为了方便测试 您可能想让类 接口或成员更易于访问 这在某种程度上是好的
  • 如何通过 Android 按钮单击运行单独的应用程序

    我尝试在 Android 应用程序中添加两个按钮 以从单独的两个应用程序订单系统和库存系统中选择一个应用程序 如图所示 我已将这两个应用程序实现为两个单独的 Android 项目 当我尝试运行此应用程序时 它会出现直到正确选择窗口 但是当按
  • 如何停止执行的 Jar 文件

    这感觉像是一个愚蠢的问题 但我似乎无法弄清楚 当我在 Windows 上运行 jar 文件时 它不会出现在任务管理器进程中 我怎样才能终止它 我已经尝试过 TASKKILL 但它对我也不起作用 On Linux ps ef grep jav
  • Karaf / Maven - 无法解决:缺少需求 osgi.wiring.package

    我无法在 Karaf 版本 3 0 1 中启动捆绑包 该包是使用 Maven 构建的并导入gson http mvnrepository com artifact com google code gson gson 2 3 1 我按照要求将
  • 如何从 Ant 启动聚合 jetty-server JAR?

    背景 免责声明 I have veryJava 经验很少 我们之前在 Ant 构建期间使用了 Jetty 6 的包装版本来处理按需静态内容 JS CSS 图像 HTML 因此我们可以使用 PhantomJS 针对 HTTP 托管环境运行单元
  • 无需登录即可直接从 Alfresco 访问文件/内容

    我的场景是这样的 我有一个使用 ALFRESCO CMS 来显示文件或图像的 Web 应用程序 我正在做的是在 Java servlet 中使用用户名和密码登录 alfresco 并且我可以获得该登录的票证 但我无法使用该票证直接从浏览器访
  • 使用 Java https 上传到 Imgur v3 错误

    我目前正在尝试使用他们当前的 API v3 上传到 imgur 但是我不断收到错误 错误 javax net ssl SSLException 证书中的主机名不匹配 api imgur com imgur com OR imgur com
  • 何时在 hibernate 中使用 DiscriminatorValue 注解

    在 hibernate 中使用 DiscriminatorValue 注释的最佳场景是什么以及何时 这两个链接最能帮助我理解继承概念 http docs oracle com javaee 6 tutorial doc bnbqn html
  • Java 的 PriorityQueue 与最小堆有何不同?

    他们为什么命名PriorityQueue如果你不能插入优先级 它看起来与堆非常相似 有什么区别吗 如果没有区别那为什么叫它PriorityQueue而不是堆 默认的PriorityQueue是用Min Heap实现的 即栈顶元素是堆中最小的

随机推荐