
io.gitee.ludii.excel.write.writer.WorkbookWriter Maven / Gradle / Ivy
package io.gitee.ludii.excel.write.writer;
import io.gitee.ludii.excel.exceptions.ExcelException;
import io.gitee.ludii.excel.support.WorkbookType;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* @author 陆迪
* @date 2022/4/25
*/
@Slf4j
public class WorkbookWriter implements AutoCloseable {
private final OutputStream outputStream;
private final Workbook workbook;
/**
* 是否是按模板写入
*/
private final boolean templateWriteModel;
public WorkbookWriter(OutputStream outputStream, InputStream templateInputStream, WorkbookType workbookType) {
this.outputStream = outputStream;
if (templateInputStream == null) {
try {
this.workbook = WorkbookFactory.create(WorkbookType.XLS.equals(workbookType));
this.templateWriteModel = false;
} catch (IOException e) {
log.error("创建工作簿失败", e);
throw new ExcelException("创建工作簿失败");
}
} else {
try {
this.workbook = WorkbookFactory.create(templateInputStream);
this.templateWriteModel = true;
} catch (IOException e) {
log.error("读取工作簿失败", e);
throw new ExcelException("读取工作簿失败");
}
}
}
public void write() {
try {
workbook.write(outputStream);
} catch (IOException e) {
log.error("workbook写入输出流失败", e);
throw new ExcelException("写入输出流失败");
}
}
Workbook getWorkbook() {
return workbook;
}
boolean isTemplateWriteModel() {
return templateWriteModel;
}
@Override
public void close() {
try {
this.workbook.close();
} catch (IOException e) {
log.error("关闭workbook失败", e);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy