簡體   English   中英

如何在 Apache poi SXSSFWorkbook 上添加自定義 SheetDataWriter?

[英]How to add custom SheetDataWriter on Apache poi SXSSFWorkbook?

我只想用我自己的 SheetDataWriter 來覆蓋下面的方法

    /**
 * Override this to translate (such as decrypt or expand) the file input stream
 * as it is being read from disk.
 * The default behavior is to to pass the stream through unmodified.
 *
 * @param fis  the stream to decorate
 * @return a decorated stream
 * @throws IOException
 * @see #decorateOutputStream(FileOutputStream)
 */
protected InputStream decorateInputStream(FileInputStream fis) throws IOException {
    return fis;
}

因為我想在設置壓縮時替換此方法:true

@Override
//GZIPInputStream default cache byte size is 512b
protected InputStream decorateInputStream(FileInputStream fis) throws IOException {
    return new GZIPInputStream(fis);
}

為什么我要替換這個? 因為我想知道緩存大小是否是在高並發(apache jmeter: 50 users , 6 循環, 加速 20) . 但問題是如何在初始化 SXSSFWorkbook 時使用我自己的 SheetDataWriter?

您是在問如何覆蓋Java中的方法嗎? 這似乎是一個非常基本的問題。

您可以擁有自己的SXSSFWorkbook class 擴展默認SXSSFWorkbook並覆蓋protected SheetDataWriter createSheetDataWriter() 在那里,如果是壓縮的臨時文件,您可以返回一個擴展的GZIPSheetDataWriter ,它會覆蓋protected InputStream decorateInputStream(FileInputStream fis)

完整的工作示例:

import java.io.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.*;

import java.util.zip.GZIPInputStream;

class OverrideSXSSFWorkbook {

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

  try (
   SXSSFWorkbook workbook = new MySXSSFWorkbook(); FileOutputStream fileout = new FileOutputStream("Excel.xlsx") ) {

   workbook.setCompressTempFiles(true);

   Sheet sheet = workbook.createSheet();
   Row row;
   Cell cell;

   row = sheet.createRow(0);
   cell = row.createCell(0);
   cell.setCellValue("CellValue");
 
   workbook.write(fileout);
   workbook.close();
   workbook.dispose();

  }
 }
}

class MySXSSFWorkbook extends SXSSFWorkbook {

 @Override
 protected SheetDataWriter createSheetDataWriter() throws IOException {

  if(isCompressTempFiles()) {
   System.out.println("GZIPSheetDataWriter");
   //return new GZIPSheetDataWriter(getSharedStringSource());

   return new GZIPSheetDataWriter(getSharedStringSource()) {

    @Override
    protected InputStream decorateInputStream(FileInputStream fis) throws IOException {
     System.out.println("overridden decorateInputStream");
     return new GZIPInputStream(fis);
    }
   };

  }
  System.out.println("default SheetDataWriter");
  return new SheetDataWriter(getSharedStringSource());

 }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM