如何在apache poi sxssfworkbook上添加自定义sheetdatawriter?

ahy6op9u  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(271)

我只想用我自己的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;
}

因为我想在设置compress:true时替换这个方法

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

为什么我要替换这个?因为我想找出缓存大小是否是降低从poi sxssf sheet??.gz到poi sxssf template??.xlsx在高并发上的写入速度的主要原因(apache jmeter:50个用户,6个循环,ramup 20)。但问题是在初始化sxssfworkbook时如何使用我自己的sheetdatawriter?

xzv2uavs

xzv2uavs1#

您是在问如何重写中的方法吗 Java ? 这似乎是一个非常基本的问题。
你可以有你自己的 SXSSFWorkbook 扩展默认值的类 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());

 }
}

相关问题