如何将 Redis DB 值写入 excel sheet?

How to write the Redis DB values into excel sheet?

我正在使用 Redis 数据库管理器,客户端是 Jedis。

我已经使用 java

执行了以下两个查询
System.out.println("Alphabets:"+Jedis.smembers("SET Name");

System.out.println("Books:"+Jedis.hgetall("key","value");

输出如下,

1.First Print Statement output

Alphabets:[A,B,C,D,]

2.Second Print Statement output

Books : Cookbook=[Vishnu,JavaBook=Balaguru,Macbook=Steve]

这里我想把上面的输出值写成一个excelsheet格式如下

标题:字母列表

No Alphabets

  1. A
  2. B
  3. C
  4. D

Title : Books List

No. Book Name. BookAuthor

  1. Cookbook. Vishnu
  2. JavaBook. Balaguru
  3. MacBook Steve

字母是 Redis SET Command to get the SET values

中的值

Book Name 是键,BookAuthor 是 Redis Hash 中的值,用于第二个打印语句输出

我看过很多教程从数组中获取值并使用 Apache excel sheet 动态写入 poi.but 我得到的结果在这里看起来不像数组。

每次我在结果中得到更多的值,有没有办法动态写入 excel。

我的问题是如何将打印的输出值传递到 excel objects 并动态写入 excel

请帮我解决这个问题。

提前感谢您的帮助。

您可以使用 Apache POI 或 Jasper Reports 来完成。

Apache 兴趣点

package q46617008;

import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.Iterator;
import java.util.Map.Entry;

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;

public class ApacheExample
{

    public void build( WorksheetExample w ) throws Exception
    {

        Workbook wb = new XSSFWorkbook( );

        Sheet s = wb.createSheet( );
        // If you need to name it:
        // String name = WorkbookUtil.createSafeSheetName( "the name!" );
        // Sheet s = wb.createSheet( name );

        Row titleRow = s.createRow( 0 );
        Cell titleCell = titleRow.createCell( 0 );
        titleCell.setCellValue( "Alphabets List" );

        Row r;
        Cell c;
        int i = 1;
        Iterator< String > alphabetsIterator = WorksheetExample.alphabets.iterator( );
        while ( alphabetsIterator.hasNext( ) )
        {
            String alphabet = alphabetsIterator.next( );
            r = s.createRow( i );
            c = r.createCell( 0 );
            c.setCellValue( alphabet );
            i++;
        }

        // Skip one line to start books list title.
        // If you need this in another sheet, just create it:
        // s = wb.createSheet();
        i++;
        titleRow = s.createRow( i );
        titleCell = titleRow.createCell( 0 );
        titleCell.setCellValue( "Books List" );

        // Skip one line to start books list.
        i++;
        Iterator< Entry< String, String > > booksIterator = WorksheetExample.books.entrySet( ).iterator( );
        while ( booksIterator.hasNext( ) )
        {
            Entry< String, String > book = booksIterator.next( );
            r = s.createRow( i );
            c = r.createCell( 0 );
            c.setCellValue( book.getKey( ) + ". " + book.getValue( ) );
            i++;
        }

        OutputStream fileOut = Files.newOutputStream( w.file, StandardOpenOption.CREATE );
        wb.write( fileOut );
        fileOut.close( );

        wb.close( );
    }

}

结果将类似于:


贾斯珀报道

您需要一份 Jasper 报告 JRXML 文件:

<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.3.1.final using JasperReports Library version 6.3.1  -->
<!-- 2017-10-13T16:31:09 -->
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="Worksheet" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="0c9a4a90-2d7f-4793-bf61-9f72221b82b4">
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="One Empty Record"/>
    <property name="net.sf.jasperreports.export.xls.white.page.background" value="false"/>
    <property name="net.sf.jasperreports.export.xls.detect.cell.type" value="true"/>
    <property name="net.sf.jasperreports.print.keep.full.text" value="true"/>
    <style name="Table_TH" mode="Opaque" backcolor="#F0F8FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
            <topPen lineWidth="0.5" lineColor="#000000"/>
            <leftPen lineWidth="0.5" lineColor="#000000"/>
            <bottomPen lineWidth="0.5" lineColor="#000000"/>
            <rightPen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="Table_CH" mode="Opaque" backcolor="#BFE1FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
            <topPen lineWidth="0.5" lineColor="#000000"/>
            <leftPen lineWidth="0.5" lineColor="#000000"/>
            <bottomPen lineWidth="0.5" lineColor="#000000"/>
            <rightPen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="Table_TD" mode="Opaque" backcolor="#FFFFFF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
            <topPen lineWidth="0.5" lineColor="#000000"/>
            <leftPen lineWidth="0.5" lineColor="#000000"/>
            <bottomPen lineWidth="0.5" lineColor="#000000"/>
            <rightPen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <subDataset name="AlphabetsDataSet" uuid="725922ca-545f-4070-b9ed-5d9cd64508ff">
        <queryString>
            <![CDATA[]]>
        </queryString>
        <field name="_THIS" class="java.lang.String"/>
    </subDataset>
    <subDataset name="BooksDataSet" uuid="f06a8881-d9b9-42dc-90c3-ee1f748045e6">
        <queryString>
            <![CDATA[]]>
        </queryString>
        <field name="_THIS" class="java.util.Map.Entry"/>
    </subDataset>
    <parameter name="Alphabets" class="java.util.Set" nestedType="String">
        <parameterDescription><![CDATA[]]></parameterDescription>
    </parameter>
    <parameter name="Books" class="java.util.Map"/>
    <queryString>
        <![CDATA[]]>
    </queryString>
    <detail>
        <band height="120" splitType="Stretch">
            <staticText>
                <reportElement positionType="Float" x="0" y="0" width="555" height="20" uuid="6b9870c0-49f9-4540-ba5e-f131def81859"/>
                <text><![CDATA[Alphabets List]]></text>
            </staticText>
            <staticText>
                <reportElement positionType="Float" x="0" y="70" width="555" height="20" uuid="5d2a371c-4141-4728-afcf-6bdd326d4a40"/>
                <text><![CDATA[Books List]]></text>
            </staticText>
            <componentElement>
                <reportElement positionType="Float" x="0" y="20" width="555" height="30" uuid="5bca4983-9df0-4eee-8a5b-9cf3d5ef6965">
                    <property name="com.jaspersoft.studio.layout" value="com.jaspersoft.studio.editor.layout.VerticalRowLayout"/>
                    <property name="com.jaspersoft.studio.table.style.table_header" value="Table_TH"/>
                    <property name="com.jaspersoft.studio.table.style.column_header" value="Table_CH"/>
                    <property name="com.jaspersoft.studio.table.style.detail" value="Table_TD"/>
                </reportElement>
                <jr:table xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd">
                    <datasetRun subDataset="AlphabetsDataSet" uuid="e998d7ad-a964-447e-b3e7-b7ebfd6ed06b">
                        <dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($P{Alphabets})]]></dataSourceExpression>
                    </datasetRun>
                    <jr:column width="120" uuid="739ad6b0-e886-4d7f-92d6-2cf0ef204ed6">
                        <property name="com.jaspersoft.studio.components.table.model.column.name" value="Column1"/>
                        <jr:detailCell style="Table_TD" height="30">
                            <textField>
                                <reportElement x="0" y="0" width="120" height="30" uuid="c02e9247-104c-426b-b538-27c048d213ac"/>
                                <box padding="5"/>
                                <textFieldExpression><![CDATA[$F{_THIS}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                </jr:table>
            </componentElement>
            <componentElement>
                <reportElement positionType="Float" x="0" y="90" width="555" height="30" uuid="1ecc6ba3-a20e-4978-aee9-4113907135c7">
                    <property name="com.jaspersoft.studio.layout" value="com.jaspersoft.studio.editor.layout.VerticalRowLayout"/>
                    <property name="com.jaspersoft.studio.table.style.table_header" value="Table_TH"/>
                    <property name="com.jaspersoft.studio.table.style.column_header" value="Table_CH"/>
                    <property name="com.jaspersoft.studio.table.style.detail" value="Table_TD"/>
                </reportElement>
                <jr:table xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd">
                    <datasetRun subDataset="BooksDataSet" uuid="c09b4524-202e-436e-b6ba-74571e14c9af">
                        <dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($P{Books}.entrySet())]]></dataSourceExpression>
                    </datasetRun>
                    <jr:column width="120" uuid="397f69ae-2f85-44fd-85fc-bca177628dab">
                        <property name="com.jaspersoft.studio.components.table.model.column.name" value="Column1"/>
                        <jr:detailCell style="Table_TD" height="30">
                            <textField>
                                <reportElement x="0" y="0" width="120" height="30" uuid="8d5fd0a8-7921-4871-8aa8-5360ac440f49"/>
                                <box padding="5"/>
                                <textFieldExpression><![CDATA[$F{_THIS}.getKey()+". "+$F{_THIS}.getValue()]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                </jr:table>
            </componentElement>
        </band>
    </detail>
</jasperReport>

对于此示例,将其保存为 Worksheet.jrxml 某处,但请记住路径,因为我们将在下一步中使用它。

对于 Java 实施:

package q46617008;

import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter;
import net.sf.jasperreports.export.SimpleExporterInput;
import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput;

public class JasperExample
{

    private Map< String, Object > parameters;

    private String filePath = "C:\Path\To\Your\Worksheet.jrxml";

    public JasperExample( ) {

        parameters = new HashMap<>( );
        // Define your locale or set it as a parameter
        parameters.put( JRParameter.REPORT_LOCALE, new Locale( "pt", "BR" ) );
        parameters.put( "Alphabets", WorksheetExample.alphabets );
        parameters.put( "Books", WorksheetExample.books );
    }

    public void exportPDF( WorksheetExample w ) throws Exception
    {

        JRDataSource reportDataSource = new JREmptyDataSource( 1 );

        JasperReport report = JasperCompileManager.compileReport( filePath );

        JasperPrint jasperPrint = JasperFillManager.fillReport( report, parameters, reportDataSource );

        JRPdfExporter exporter = new JRPdfExporter( );
        exporter.setExporterInput( new SimpleExporterInput( jasperPrint ) );
        exporter.setExporterOutput( new SimpleOutputStreamExporterOutput( Files.newOutputStream( w.file, StandardOpenOption.CREATE ) ) );

        exporter.exportReport( );
    }

    public void exportXLSX( WorksheetExample w ) throws Exception
    {

        JRDataSource reportDataSource = new JREmptyDataSource( 1 );

        JasperReport report = JasperCompileManager.compileReport( filePath );

        JasperPrint jasperPrint = JasperFillManager.fillReport( report, parameters, reportDataSource );

        JRXlsxExporter exporter = new JRXlsxExporter( );
        exporter.setExporterInput( new SimpleExporterInput( jasperPrint ) );
        exporter.setExporterOutput( new SimpleOutputStreamExporterOutput( Files.newOutputStream( w.file, StandardOpenOption.CREATE ) ) );

        exporter.exportReport( );
    }

}

结果将类似于:

在左侧,您会看到 XLSX 输出。右边是PDF版。

当然还有很多space可以优化。
例如,您可以保存编译后的 JRXML 并加载它,这比每次需要时都编译它要快得多。


运行它

如果你需要一个简单的 class 到 运行 这两个例子,使用这个:

package q46617008;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class WorksheetExample
{

    public static final Set< String > alphabets = new HashSet<>( );

    public static final Map< String, String > books = new HashMap<>( );

    public final Path file;

    public WorksheetExample( String fileName ) {
        file = Paths.get( "C:", "Path", "To", "Your", fileName );
    }

    static
    {
        alphabets.add( "A" );
        alphabets.add( "B" );
        alphabets.add( "C" );
        alphabets.add( "D" );

        books.put( "Cookbook", "Vishnu" );
        books.put( "JavaBook", "Balaguru" );
        books.put( "MacBook", "Steve" );
    }

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

        WorksheetExample w;

        w = new WorksheetExample( "ApacheExample.xlsx" );
        new ApacheExample( ).build( w );

        w = new WorksheetExample( "JasperExample.xlsx" );
        new JasperExample( ).exportXLSX( w );

        w = new WorksheetExample( "JasperExample.pdf" );
        new JasperExample( ).exportPDF( w );
    }

}