mirror of https://github.com/apache/poi.git
convert tabs to spaces
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1890117 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
parent
f21019db12
commit
95279ea034
|
@ -35,33 +35,33 @@ import org.apache.poi.hsmf.exceptions.ChunkNotFoundException;
|
|||
@SuppressWarnings({"java:S106","java:S4823"})
|
||||
public class Msg2txt {
|
||||
|
||||
/**
|
||||
* The stem used to create file names for the text file and the directory
|
||||
* that contains the attachments.
|
||||
*/
|
||||
private String fileNameStem;
|
||||
/**
|
||||
* The stem used to create file names for the text file and the directory
|
||||
* that contains the attachments.
|
||||
*/
|
||||
private String fileNameStem;
|
||||
|
||||
/**
|
||||
* The Outlook MSG file being processed.
|
||||
*/
|
||||
private MAPIMessage msg;
|
||||
/**
|
||||
* The Outlook MSG file being processed.
|
||||
*/
|
||||
private MAPIMessage msg;
|
||||
|
||||
public Msg2txt(String fileName) throws IOException {
|
||||
fileNameStem = fileName;
|
||||
if(fileNameStem.endsWith(".msg") || fileNameStem.endsWith(".MSG")) {
|
||||
fileNameStem = fileNameStem.substring(0, fileNameStem.length() - 4);
|
||||
}
|
||||
msg = new MAPIMessage(fileName);
|
||||
}
|
||||
public Msg2txt(String fileName) throws IOException {
|
||||
fileNameStem = fileName;
|
||||
if(fileNameStem.endsWith(".msg") || fileNameStem.endsWith(".MSG")) {
|
||||
fileNameStem = fileNameStem.substring(0, fileNameStem.length() - 4);
|
||||
}
|
||||
msg = new MAPIMessage(fileName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes the message.
|
||||
*
|
||||
* @throws IOException if an exception occurs while writing the message out
|
||||
*/
|
||||
public void processMessage() throws IOException {
|
||||
String txtFileName = fileNameStem + ".txt";
|
||||
String attDirName = fileNameStem + "-att";
|
||||
/**
|
||||
* Processes the message.
|
||||
*
|
||||
* @throws IOException if an exception occurs while writing the message out
|
||||
*/
|
||||
public void processMessage() throws IOException {
|
||||
String txtFileName = fileNameStem + ".txt";
|
||||
String attDirName = fileNameStem + "-att";
|
||||
try (PrintWriter txtOut = new PrintWriter(txtFileName, "UTF-8")) {
|
||||
try {
|
||||
String displayFrom = msg.getDisplayFrom();
|
||||
|
@ -112,47 +112,47 @@ public class Msg2txt {
|
|||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes a single attachment: reads it from the Outlook MSG file and
|
||||
* writes it to disk as an individual file.
|
||||
*
|
||||
* @param attachment the chunk group describing the attachment
|
||||
* @param dir the directory in which to write the attachment file
|
||||
* @throws IOException when any of the file operations fails
|
||||
*/
|
||||
public void processAttachment(AttachmentChunks attachment,
|
||||
File dir) throws IOException {
|
||||
String fileName = attachment.getAttachFileName().toString();
|
||||
if(attachment.getAttachLongFileName() != null) {
|
||||
fileName = attachment.getAttachLongFileName().toString();
|
||||
}
|
||||
/**
|
||||
* Processes a single attachment: reads it from the Outlook MSG file and
|
||||
* writes it to disk as an individual file.
|
||||
*
|
||||
* @param attachment the chunk group describing the attachment
|
||||
* @param dir the directory in which to write the attachment file
|
||||
* @throws IOException when any of the file operations fails
|
||||
*/
|
||||
public void processAttachment(AttachmentChunks attachment,
|
||||
File dir) throws IOException {
|
||||
String fileName = attachment.getAttachFileName().toString();
|
||||
if(attachment.getAttachLongFileName() != null) {
|
||||
fileName = attachment.getAttachLongFileName().toString();
|
||||
}
|
||||
|
||||
File f = new File(dir, fileName);
|
||||
File f = new File(dir, fileName);
|
||||
try (OutputStream fileOut = new FileOutputStream(f)) {
|
||||
fileOut.write(attachment.getAttachData().getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes the list of arguments as a list of names of Outlook MSG files.
|
||||
*
|
||||
* @param args the list of MSG files to process
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
if(args.length <= 0) {
|
||||
System.err.println("No files names provided");
|
||||
} else {
|
||||
for (String arg : args) {
|
||||
try {
|
||||
Msg2txt processor = new Msg2txt(arg);
|
||||
processor.processMessage();
|
||||
} catch (IOException e) {
|
||||
System.err.println("Could not process " + arg + ": " + e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Processes the list of arguments as a list of names of Outlook MSG files.
|
||||
*
|
||||
* @param args the list of MSG files to process
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
if(args.length <= 0) {
|
||||
System.err.println("No files names provided");
|
||||
} else {
|
||||
for (String arg : args) {
|
||||
try {
|
||||
Msg2txt processor = new Msg2txt(arg);
|
||||
processor.processMessage();
|
||||
} catch (IOException e) {
|
||||
System.err.println("Could not process " + arg + ": " + e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -53,277 +53,277 @@ import org.apache.poi.poifs.filesystem.POIFSFileSystem;
|
|||
*/
|
||||
@SuppressWarnings({"java:S106","java:S4823"})
|
||||
public class XLS2CSVmra implements HSSFListener {
|
||||
private final int minColumns;
|
||||
private final POIFSFileSystem fs;
|
||||
private final PrintStream output;
|
||||
private final int minColumns;
|
||||
private final POIFSFileSystem fs;
|
||||
private final PrintStream output;
|
||||
|
||||
private int lastRowNumber;
|
||||
private int lastColumnNumber;
|
||||
private int lastRowNumber;
|
||||
private int lastColumnNumber;
|
||||
|
||||
/** Should we output the formula, or the value it has? */
|
||||
private final boolean outputFormulaValues = true;
|
||||
/** Should we output the formula, or the value it has? */
|
||||
private final boolean outputFormulaValues = true;
|
||||
|
||||
/** For parsing Formulas */
|
||||
private SheetRecordCollectingListener workbookBuildingListener;
|
||||
private HSSFWorkbook stubWorkbook;
|
||||
/** For parsing Formulas */
|
||||
private SheetRecordCollectingListener workbookBuildingListener;
|
||||
private HSSFWorkbook stubWorkbook;
|
||||
|
||||
// Records we pick up as we process
|
||||
private SSTRecord sstRecord;
|
||||
private FormatTrackingHSSFListener formatListener;
|
||||
// Records we pick up as we process
|
||||
private SSTRecord sstRecord;
|
||||
private FormatTrackingHSSFListener formatListener;
|
||||
|
||||
/** So we known which sheet we're on */
|
||||
private int sheetIndex = -1;
|
||||
private BoundSheetRecord[] orderedBSRs;
|
||||
private final List<BoundSheetRecord> boundSheetRecords = new ArrayList<>();
|
||||
/** So we known which sheet we're on */
|
||||
private int sheetIndex = -1;
|
||||
private BoundSheetRecord[] orderedBSRs;
|
||||
private final List<BoundSheetRecord> boundSheetRecords = new ArrayList<>();
|
||||
|
||||
// For handling formulas with string results
|
||||
private int nextRow;
|
||||
private int nextColumn;
|
||||
private boolean outputNextStringRecord;
|
||||
// For handling formulas with string results
|
||||
private int nextRow;
|
||||
private int nextColumn;
|
||||
private boolean outputNextStringRecord;
|
||||
|
||||
/**
|
||||
* Creates a new XLS -> CSV converter
|
||||
* @param fs The POIFSFileSystem to process
|
||||
* @param output The PrintStream to output the CSV to
|
||||
* @param minColumns The minimum number of columns to output, or -1 for no minimum
|
||||
*/
|
||||
public XLS2CSVmra(POIFSFileSystem fs, PrintStream output, int minColumns) {
|
||||
this.fs = fs;
|
||||
this.output = output;
|
||||
this.minColumns = minColumns;
|
||||
}
|
||||
/**
|
||||
* Creates a new XLS -> CSV converter
|
||||
* @param fs The POIFSFileSystem to process
|
||||
* @param output The PrintStream to output the CSV to
|
||||
* @param minColumns The minimum number of columns to output, or -1 for no minimum
|
||||
*/
|
||||
public XLS2CSVmra(POIFSFileSystem fs, PrintStream output, int minColumns) {
|
||||
this.fs = fs;
|
||||
this.output = output;
|
||||
this.minColumns = minColumns;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new XLS -> CSV converter
|
||||
* @param filename The file to process
|
||||
* @param minColumns The minimum number of columns to output, or -1 for no minimum
|
||||
*
|
||||
* @throws IOException if the file cannot be read or parsing the file fails
|
||||
*/
|
||||
public XLS2CSVmra(String filename, int minColumns) throws IOException {
|
||||
this(
|
||||
new POIFSFileSystem(new FileInputStream(filename)),
|
||||
System.out, minColumns
|
||||
);
|
||||
}
|
||||
/**
|
||||
* Creates a new XLS -> CSV converter
|
||||
* @param filename The file to process
|
||||
* @param minColumns The minimum number of columns to output, or -1 for no minimum
|
||||
*
|
||||
* @throws IOException if the file cannot be read or parsing the file fails
|
||||
*/
|
||||
public XLS2CSVmra(String filename, int minColumns) throws IOException {
|
||||
this(
|
||||
new POIFSFileSystem(new FileInputStream(filename)),
|
||||
System.out, minColumns
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initiates the processing of the XLS file to CSV
|
||||
*
|
||||
* @throws IOException if the workbook contained errors
|
||||
*/
|
||||
public void process() throws IOException {
|
||||
MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener(this);
|
||||
formatListener = new FormatTrackingHSSFListener(listener);
|
||||
/**
|
||||
* Initiates the processing of the XLS file to CSV
|
||||
*
|
||||
* @throws IOException if the workbook contained errors
|
||||
*/
|
||||
public void process() throws IOException {
|
||||
MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener(this);
|
||||
formatListener = new FormatTrackingHSSFListener(listener);
|
||||
|
||||
HSSFEventFactory factory = new HSSFEventFactory();
|
||||
HSSFRequest request = new HSSFRequest();
|
||||
HSSFEventFactory factory = new HSSFEventFactory();
|
||||
HSSFRequest request = new HSSFRequest();
|
||||
|
||||
if(outputFormulaValues) {
|
||||
request.addListenerForAllRecords(formatListener);
|
||||
} else {
|
||||
workbookBuildingListener = new SheetRecordCollectingListener(formatListener);
|
||||
request.addListenerForAllRecords(workbookBuildingListener);
|
||||
}
|
||||
if(outputFormulaValues) {
|
||||
request.addListenerForAllRecords(formatListener);
|
||||
} else {
|
||||
workbookBuildingListener = new SheetRecordCollectingListener(formatListener);
|
||||
request.addListenerForAllRecords(workbookBuildingListener);
|
||||
}
|
||||
|
||||
factory.processWorkbookEvents(request, fs);
|
||||
}
|
||||
factory.processWorkbookEvents(request, fs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Main HSSFListener method, processes events, and outputs the
|
||||
* CSV as the file is processed.
|
||||
*/
|
||||
@Override
|
||||
/**
|
||||
* Main HSSFListener method, processes events, and outputs the
|
||||
* CSV as the file is processed.
|
||||
*/
|
||||
@Override
|
||||
public void processRecord(org.apache.poi.hssf.record.Record record) {
|
||||
int thisRow = -1;
|
||||
int thisColumn = -1;
|
||||
String thisStr = null;
|
||||
int thisRow = -1;
|
||||
int thisColumn = -1;
|
||||
String thisStr = null;
|
||||
|
||||
switch (record.getSid())
|
||||
{
|
||||
case BoundSheetRecord.sid:
|
||||
boundSheetRecords.add((BoundSheetRecord)record);
|
||||
break;
|
||||
case BOFRecord.sid:
|
||||
BOFRecord br = (BOFRecord)record;
|
||||
if(br.getType() == BOFRecord.TYPE_WORKSHEET) {
|
||||
// Create sub workbook if required
|
||||
if(workbookBuildingListener != null && stubWorkbook == null) {
|
||||
stubWorkbook = workbookBuildingListener.getStubHSSFWorkbook();
|
||||
}
|
||||
switch (record.getSid())
|
||||
{
|
||||
case BoundSheetRecord.sid:
|
||||
boundSheetRecords.add((BoundSheetRecord)record);
|
||||
break;
|
||||
case BOFRecord.sid:
|
||||
BOFRecord br = (BOFRecord)record;
|
||||
if(br.getType() == BOFRecord.TYPE_WORKSHEET) {
|
||||
// Create sub workbook if required
|
||||
if(workbookBuildingListener != null && stubWorkbook == null) {
|
||||
stubWorkbook = workbookBuildingListener.getStubHSSFWorkbook();
|
||||
}
|
||||
|
||||
// Output the worksheet name
|
||||
// Works by ordering the BSRs by the location of
|
||||
// their BOFRecords, and then knowing that we
|
||||
// process BOFRecords in byte offset order
|
||||
sheetIndex++;
|
||||
if(orderedBSRs == null) {
|
||||
orderedBSRs = BoundSheetRecord.orderByBofPosition(boundSheetRecords);
|
||||
}
|
||||
output.println();
|
||||
output.println(
|
||||
orderedBSRs[sheetIndex].getSheetname() +
|
||||
" [" + (sheetIndex+1) + "]:"
|
||||
);
|
||||
}
|
||||
break;
|
||||
// Output the worksheet name
|
||||
// Works by ordering the BSRs by the location of
|
||||
// their BOFRecords, and then knowing that we
|
||||
// process BOFRecords in byte offset order
|
||||
sheetIndex++;
|
||||
if(orderedBSRs == null) {
|
||||
orderedBSRs = BoundSheetRecord.orderByBofPosition(boundSheetRecords);
|
||||
}
|
||||
output.println();
|
||||
output.println(
|
||||
orderedBSRs[sheetIndex].getSheetname() +
|
||||
" [" + (sheetIndex+1) + "]:"
|
||||
);
|
||||
}
|
||||
break;
|
||||
|
||||
case SSTRecord.sid:
|
||||
sstRecord = (SSTRecord) record;
|
||||
break;
|
||||
case SSTRecord.sid:
|
||||
sstRecord = (SSTRecord) record;
|
||||
break;
|
||||
|
||||
case BlankRecord.sid:
|
||||
BlankRecord brec = (BlankRecord) record;
|
||||
case BlankRecord.sid:
|
||||
BlankRecord brec = (BlankRecord) record;
|
||||
|
||||
thisRow = brec.getRow();
|
||||
thisColumn = brec.getColumn();
|
||||
thisStr = "";
|
||||
break;
|
||||
case BoolErrRecord.sid:
|
||||
BoolErrRecord berec = (BoolErrRecord) record;
|
||||
thisRow = brec.getRow();
|
||||
thisColumn = brec.getColumn();
|
||||
thisStr = "";
|
||||
break;
|
||||
case BoolErrRecord.sid:
|
||||
BoolErrRecord berec = (BoolErrRecord) record;
|
||||
|
||||
thisRow = berec.getRow();
|
||||
thisColumn = berec.getColumn();
|
||||
thisStr = "";
|
||||
break;
|
||||
thisRow = berec.getRow();
|
||||
thisColumn = berec.getColumn();
|
||||
thisStr = "";
|
||||
break;
|
||||
|
||||
case FormulaRecord.sid:
|
||||
FormulaRecord frec = (FormulaRecord) record;
|
||||
case FormulaRecord.sid:
|
||||
FormulaRecord frec = (FormulaRecord) record;
|
||||
|
||||
thisRow = frec.getRow();
|
||||
thisColumn = frec.getColumn();
|
||||
thisRow = frec.getRow();
|
||||
thisColumn = frec.getColumn();
|
||||
|
||||
if(outputFormulaValues) {
|
||||
if(Double.isNaN( frec.getValue() )) {
|
||||
// Formula result is a string
|
||||
// This is stored in the next record
|
||||
outputNextStringRecord = true;
|
||||
nextRow = frec.getRow();
|
||||
nextColumn = frec.getColumn();
|
||||
} else {
|
||||
thisStr = formatListener.formatNumberDateCell(frec);
|
||||
}
|
||||
} else {
|
||||
thisStr = '"' +
|
||||
HSSFFormulaParser.toFormulaString(stubWorkbook, frec.getParsedExpression()) + '"';
|
||||
}
|
||||
break;
|
||||
case StringRecord.sid:
|
||||
if(outputNextStringRecord) {
|
||||
// String for formula
|
||||
StringRecord srec = (StringRecord)record;
|
||||
thisStr = srec.getString();
|
||||
thisRow = nextRow;
|
||||
thisColumn = nextColumn;
|
||||
outputNextStringRecord = false;
|
||||
}
|
||||
break;
|
||||
if(outputFormulaValues) {
|
||||
if(Double.isNaN( frec.getValue() )) {
|
||||
// Formula result is a string
|
||||
// This is stored in the next record
|
||||
outputNextStringRecord = true;
|
||||
nextRow = frec.getRow();
|
||||
nextColumn = frec.getColumn();
|
||||
} else {
|
||||
thisStr = formatListener.formatNumberDateCell(frec);
|
||||
}
|
||||
} else {
|
||||
thisStr = '"' +
|
||||
HSSFFormulaParser.toFormulaString(stubWorkbook, frec.getParsedExpression()) + '"';
|
||||
}
|
||||
break;
|
||||
case StringRecord.sid:
|
||||
if(outputNextStringRecord) {
|
||||
// String for formula
|
||||
StringRecord srec = (StringRecord)record;
|
||||
thisStr = srec.getString();
|
||||
thisRow = nextRow;
|
||||
thisColumn = nextColumn;
|
||||
outputNextStringRecord = false;
|
||||
}
|
||||
break;
|
||||
|
||||
case LabelRecord.sid:
|
||||
LabelRecord lrec = (LabelRecord) record;
|
||||
case LabelRecord.sid:
|
||||
LabelRecord lrec = (LabelRecord) record;
|
||||
|
||||
thisRow = lrec.getRow();
|
||||
thisColumn = lrec.getColumn();
|
||||
thisStr = '"' + lrec.getValue() + '"';
|
||||
break;
|
||||
case LabelSSTRecord.sid:
|
||||
LabelSSTRecord lsrec = (LabelSSTRecord) record;
|
||||
thisRow = lrec.getRow();
|
||||
thisColumn = lrec.getColumn();
|
||||
thisStr = '"' + lrec.getValue() + '"';
|
||||
break;
|
||||
case LabelSSTRecord.sid:
|
||||
LabelSSTRecord lsrec = (LabelSSTRecord) record;
|
||||
|
||||
thisRow = lsrec.getRow();
|
||||
thisColumn = lsrec.getColumn();
|
||||
if(sstRecord == null) {
|
||||
thisStr = '"' + "(No SST Record, can't identify string)" + '"';
|
||||
} else {
|
||||
thisStr = '"' + sstRecord.getString(lsrec.getSSTIndex()).toString() + '"';
|
||||
}
|
||||
break;
|
||||
case NoteRecord.sid:
|
||||
NoteRecord nrec = (NoteRecord) record;
|
||||
thisRow = lsrec.getRow();
|
||||
thisColumn = lsrec.getColumn();
|
||||
if(sstRecord == null) {
|
||||
thisStr = '"' + "(No SST Record, can't identify string)" + '"';
|
||||
} else {
|
||||
thisStr = '"' + sstRecord.getString(lsrec.getSSTIndex()).toString() + '"';
|
||||
}
|
||||
break;
|
||||
case NoteRecord.sid:
|
||||
NoteRecord nrec = (NoteRecord) record;
|
||||
|
||||
thisRow = nrec.getRow();
|
||||
thisColumn = nrec.getColumn();
|
||||
// TODO: Find object to match nrec.getShapeId()
|
||||
thisStr = '"' + "(TODO)" + '"';
|
||||
break;
|
||||
case NumberRecord.sid:
|
||||
NumberRecord numrec = (NumberRecord) record;
|
||||
thisRow = nrec.getRow();
|
||||
thisColumn = nrec.getColumn();
|
||||
// TODO: Find object to match nrec.getShapeId()
|
||||
thisStr = '"' + "(TODO)" + '"';
|
||||
break;
|
||||
case NumberRecord.sid:
|
||||
NumberRecord numrec = (NumberRecord) record;
|
||||
|
||||
thisRow = numrec.getRow();
|
||||
thisColumn = numrec.getColumn();
|
||||
thisRow = numrec.getRow();
|
||||
thisColumn = numrec.getColumn();
|
||||
|
||||
// Format
|
||||
thisStr = formatListener.formatNumberDateCell(numrec);
|
||||
break;
|
||||
case RKRecord.sid:
|
||||
RKRecord rkrec = (RKRecord) record;
|
||||
// Format
|
||||
thisStr = formatListener.formatNumberDateCell(numrec);
|
||||
break;
|
||||
case RKRecord.sid:
|
||||
RKRecord rkrec = (RKRecord) record;
|
||||
|
||||
thisRow = rkrec.getRow();
|
||||
thisColumn = rkrec.getColumn();
|
||||
thisStr = '"' + "(TODO)" + '"';
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
thisRow = rkrec.getRow();
|
||||
thisColumn = rkrec.getColumn();
|
||||
thisStr = '"' + "(TODO)" + '"';
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
// Handle new row
|
||||
if(thisRow != -1 && thisRow != lastRowNumber) {
|
||||
lastColumnNumber = -1;
|
||||
}
|
||||
// Handle new row
|
||||
if(thisRow != -1 && thisRow != lastRowNumber) {
|
||||
lastColumnNumber = -1;
|
||||
}
|
||||
|
||||
// Handle missing column
|
||||
if(record instanceof MissingCellDummyRecord) {
|
||||
MissingCellDummyRecord mc = (MissingCellDummyRecord)record;
|
||||
thisRow = mc.getRow();
|
||||
thisColumn = mc.getColumn();
|
||||
thisStr = "";
|
||||
}
|
||||
// Handle missing column
|
||||
if(record instanceof MissingCellDummyRecord) {
|
||||
MissingCellDummyRecord mc = (MissingCellDummyRecord)record;
|
||||
thisRow = mc.getRow();
|
||||
thisColumn = mc.getColumn();
|
||||
thisStr = "";
|
||||
}
|
||||
|
||||
// If we got something to print out, do so
|
||||
if(thisStr != null) {
|
||||
if(thisColumn > 0) {
|
||||
output.print(',');
|
||||
}
|
||||
output.print(thisStr);
|
||||
}
|
||||
// If we got something to print out, do so
|
||||
if(thisStr != null) {
|
||||
if(thisColumn > 0) {
|
||||
output.print(',');
|
||||
}
|
||||
output.print(thisStr);
|
||||
}
|
||||
|
||||
// Update column and row count
|
||||
if(thisRow > -1)
|
||||
lastRowNumber = thisRow;
|
||||
if(thisColumn > -1)
|
||||
lastColumnNumber = thisColumn;
|
||||
// Update column and row count
|
||||
if(thisRow > -1)
|
||||
lastRowNumber = thisRow;
|
||||
if(thisColumn > -1)
|
||||
lastColumnNumber = thisColumn;
|
||||
|
||||
// Handle end of row
|
||||
if(record instanceof LastCellOfRowDummyRecord) {
|
||||
// Print out any missing commas if needed
|
||||
if(minColumns > 0) {
|
||||
// Columns are 0 based
|
||||
if(lastColumnNumber == -1) { lastColumnNumber = 0; }
|
||||
for(int i=lastColumnNumber; i<(minColumns); i++) {
|
||||
output.print(',');
|
||||
}
|
||||
}
|
||||
// Handle end of row
|
||||
if(record instanceof LastCellOfRowDummyRecord) {
|
||||
// Print out any missing commas if needed
|
||||
if(minColumns > 0) {
|
||||
// Columns are 0 based
|
||||
if(lastColumnNumber == -1) { lastColumnNumber = 0; }
|
||||
for(int i=lastColumnNumber; i<(minColumns); i++) {
|
||||
output.print(',');
|
||||
}
|
||||
}
|
||||
|
||||
// We're onto a new row
|
||||
lastColumnNumber = -1;
|
||||
// We're onto a new row
|
||||
lastColumnNumber = -1;
|
||||
|
||||
// End the row
|
||||
output.println();
|
||||
}
|
||||
}
|
||||
// End the row
|
||||
output.println();
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
if(args.length < 1) {
|
||||
System.err.println("Use:");
|
||||
System.err.println(" XLS2CSVmra <xls file> [min columns]");
|
||||
System.exit(1);
|
||||
}
|
||||
public static void main(String[] args) throws Exception {
|
||||
if(args.length < 1) {
|
||||
System.err.println("Use:");
|
||||
System.err.println(" XLS2CSVmra <xls file> [min columns]");
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
int minColumns = -1;
|
||||
if(args.length >= 2) {
|
||||
minColumns = Integer.parseInt(args[1]);
|
||||
}
|
||||
int minColumns = -1;
|
||||
if(args.length >= 2) {
|
||||
minColumns = Integer.parseInt(args[1]);
|
||||
}
|
||||
|
||||
XLS2CSVmra xls2csv = new XLS2CSVmra(args[0], minColumns);
|
||||
xls2csv.process();
|
||||
}
|
||||
XLS2CSVmra xls2csv = new XLS2CSVmra(args[0], minColumns);
|
||||
xls2csv.process();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -43,92 +43,92 @@ import org.apache.poi.ss.util.CellRangeAddress;
|
|||
@SuppressWarnings({"java:S106","java:S4823"})
|
||||
public final class HSSFReadWrite {
|
||||
|
||||
private HSSFReadWrite() {}
|
||||
private HSSFReadWrite() {}
|
||||
|
||||
/**
|
||||
* creates an {@link HSSFWorkbook} with the specified OS filename.
|
||||
*/
|
||||
private static HSSFWorkbook readFile(String filename) throws IOException {
|
||||
try (FileInputStream fis = new FileInputStream(filename)) {
|
||||
return new HSSFWorkbook(fis); // NOSONAR - should not be closed here
|
||||
}
|
||||
}
|
||||
/**
|
||||
* creates an {@link HSSFWorkbook} with the specified OS filename.
|
||||
*/
|
||||
private static HSSFWorkbook readFile(String filename) throws IOException {
|
||||
try (FileInputStream fis = new FileInputStream(filename)) {
|
||||
return new HSSFWorkbook(fis); // NOSONAR - should not be closed here
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* given a filename this outputs a sample sheet with just a set of
|
||||
* rows/cells.
|
||||
*/
|
||||
private static void testCreateSampleSheet(String outputFilename) throws IOException {
|
||||
try (HSSFWorkbook wb = new HSSFWorkbook();
|
||||
FileOutputStream out = new FileOutputStream(outputFilename)) {
|
||||
HSSFSheet s = wb.createSheet();
|
||||
HSSFCellStyle cs = wb.createCellStyle();
|
||||
HSSFCellStyle cs2 = wb.createCellStyle();
|
||||
HSSFCellStyle cs3 = wb.createCellStyle();
|
||||
HSSFFont f = wb.createFont();
|
||||
HSSFFont f2 = wb.createFont();
|
||||
/**
|
||||
* given a filename this outputs a sample sheet with just a set of
|
||||
* rows/cells.
|
||||
*/
|
||||
private static void testCreateSampleSheet(String outputFilename) throws IOException {
|
||||
try (HSSFWorkbook wb = new HSSFWorkbook();
|
||||
FileOutputStream out = new FileOutputStream(outputFilename)) {
|
||||
HSSFSheet s = wb.createSheet();
|
||||
HSSFCellStyle cs = wb.createCellStyle();
|
||||
HSSFCellStyle cs2 = wb.createCellStyle();
|
||||
HSSFCellStyle cs3 = wb.createCellStyle();
|
||||
HSSFFont f = wb.createFont();
|
||||
HSSFFont f2 = wb.createFont();
|
||||
|
||||
f.setFontHeightInPoints((short) 12);
|
||||
f.setColor((short) 0xA);
|
||||
f.setBold(true);
|
||||
f2.setFontHeightInPoints((short) 10);
|
||||
f2.setColor((short) 0xf);
|
||||
f2.setBold(true);
|
||||
cs.setFont(f);
|
||||
cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)"));
|
||||
cs2.setBorderBottom(BorderStyle.THIN);
|
||||
cs2.setFillPattern(FillPatternType.SOLID_FOREGROUND);
|
||||
cs2.setFillForegroundColor((short) 0xA);
|
||||
cs2.setFont(f2);
|
||||
wb.setSheetName(0, "HSSF Test");
|
||||
int rownum;
|
||||
for (rownum = 0; rownum < 300; rownum++) {
|
||||
HSSFRow r = s.createRow(rownum);
|
||||
if ((rownum % 2) == 0) {
|
||||
r.setHeight((short) 0x249);
|
||||
}
|
||||
f.setFontHeightInPoints((short) 12);
|
||||
f.setColor((short) 0xA);
|
||||
f.setBold(true);
|
||||
f2.setFontHeightInPoints((short) 10);
|
||||
f2.setColor((short) 0xf);
|
||||
f2.setBold(true);
|
||||
cs.setFont(f);
|
||||
cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)"));
|
||||
cs2.setBorderBottom(BorderStyle.THIN);
|
||||
cs2.setFillPattern(FillPatternType.SOLID_FOREGROUND);
|
||||
cs2.setFillForegroundColor((short) 0xA);
|
||||
cs2.setFont(f2);
|
||||
wb.setSheetName(0, "HSSF Test");
|
||||
int rownum;
|
||||
for (rownum = 0; rownum < 300; rownum++) {
|
||||
HSSFRow r = s.createRow(rownum);
|
||||
if ((rownum % 2) == 0) {
|
||||
r.setHeight((short) 0x249);
|
||||
}
|
||||
|
||||
for (int cellnum = 0; cellnum < 50; cellnum += 2) {
|
||||
HSSFCell c = r.createCell(cellnum);
|
||||
c.setCellValue((rownum * 10000.0) + cellnum
|
||||
+ (rownum / 1000.0) + (cellnum / 10000.0));
|
||||
if ((rownum % 2) == 0) {
|
||||
c.setCellStyle(cs);
|
||||
}
|
||||
c = r.createCell(cellnum + 1);
|
||||
c.setCellValue(new HSSFRichTextString("TEST"));
|
||||
// 50 characters divided by 1/20th of a point
|
||||
s.setColumnWidth(cellnum + 1, (int) (50 * 8 / 0.05));
|
||||
if ((rownum % 2) == 0) {
|
||||
c.setCellStyle(cs2);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (int cellnum = 0; cellnum < 50; cellnum += 2) {
|
||||
HSSFCell c = r.createCell(cellnum);
|
||||
c.setCellValue((rownum * 10000.0) + cellnum
|
||||
+ (rownum / 1000.0) + (cellnum / 10000.0));
|
||||
if ((rownum % 2) == 0) {
|
||||
c.setCellStyle(cs);
|
||||
}
|
||||
c = r.createCell(cellnum + 1);
|
||||
c.setCellValue(new HSSFRichTextString("TEST"));
|
||||
// 50 characters divided by 1/20th of a point
|
||||
s.setColumnWidth(cellnum + 1, (int) (50 * 8 / 0.05));
|
||||
if ((rownum % 2) == 0) {
|
||||
c.setCellStyle(cs2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// draw a thick black border on the row at the bottom using BLANKS
|
||||
rownum++;
|
||||
rownum++;
|
||||
HSSFRow r = s.createRow(rownum);
|
||||
cs3.setBorderBottom(BorderStyle.THICK);
|
||||
for (int cellnum = 0; cellnum < 50; cellnum++) {
|
||||
HSSFCell c = r.createCell(cellnum);
|
||||
c.setCellStyle(cs3);
|
||||
}
|
||||
s.addMergedRegion(new CellRangeAddress(0, 3, 0, 3));
|
||||
s.addMergedRegion(new CellRangeAddress(100, 110, 100, 110));
|
||||
// draw a thick black border on the row at the bottom using BLANKS
|
||||
rownum++;
|
||||
rownum++;
|
||||
HSSFRow r = s.createRow(rownum);
|
||||
cs3.setBorderBottom(BorderStyle.THICK);
|
||||
for (int cellnum = 0; cellnum < 50; cellnum++) {
|
||||
HSSFCell c = r.createCell(cellnum);
|
||||
c.setCellStyle(cs3);
|
||||
}
|
||||
s.addMergedRegion(new CellRangeAddress(0, 3, 0, 3));
|
||||
s.addMergedRegion(new CellRangeAddress(100, 110, 100, 110));
|
||||
|
||||
// end draw thick black border
|
||||
// create a sheet, set its title then delete it
|
||||
wb.createSheet();
|
||||
wb.setSheetName(1, "DeletedSheet");
|
||||
wb.removeSheetAt(1);
|
||||
// end draw thick black border
|
||||
// create a sheet, set its title then delete it
|
||||
wb.createSheet();
|
||||
wb.setSheetName(1, "DeletedSheet");
|
||||
wb.removeSheetAt(1);
|
||||
|
||||
// end deleted sheet
|
||||
wb.write(out);
|
||||
}
|
||||
}
|
||||
// end deleted sheet
|
||||
wb.write(out);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
/**
|
||||
* Method main
|
||||
*
|
||||
* Given 1 argument takes that as the filename, inputs it and dumps the
|
||||
|
@ -148,104 +148,104 @@ public final class HSSFReadWrite {
|
|||
* "MODIFIED CELL" then writes it out. Hence this is "modify test 1". If you
|
||||
* take the output from the write test, you'll have a valid scenario.
|
||||
*/
|
||||
public static void main(String[] args) throws Exception {
|
||||
if (args.length < 1) {
|
||||
System.err.println("At least one argument expected");
|
||||
return;
|
||||
}
|
||||
public static void main(String[] args) throws Exception {
|
||||
if (args.length < 1) {
|
||||
System.err.println("At least one argument expected");
|
||||
return;
|
||||
}
|
||||
|
||||
String fileName = args[0];
|
||||
if (args.length < 2) {
|
||||
String fileName = args[0];
|
||||
if (args.length < 2) {
|
||||
|
||||
try (HSSFWorkbook wb = HSSFReadWrite.readFile(fileName)) {
|
||||
System.out.println("Data dump:\n");
|
||||
try (HSSFWorkbook wb = HSSFReadWrite.readFile(fileName)) {
|
||||
System.out.println("Data dump:\n");
|
||||
|
||||
for (int k = 0; k < wb.getNumberOfSheets(); k++) {
|
||||
HSSFSheet sheet = wb.getSheetAt(k);
|
||||
int rows = sheet.getPhysicalNumberOfRows();
|
||||
System.out.println("Sheet " + k + " \"" + wb.getSheetName(k) + "\" has " + rows + " row(s).");
|
||||
for (int r = 0; r < rows; r++) {
|
||||
HSSFRow row = sheet.getRow(r);
|
||||
if (row == null) {
|
||||
continue;
|
||||
}
|
||||
for (int k = 0; k < wb.getNumberOfSheets(); k++) {
|
||||
HSSFSheet sheet = wb.getSheetAt(k);
|
||||
int rows = sheet.getPhysicalNumberOfRows();
|
||||
System.out.println("Sheet " + k + " \"" + wb.getSheetName(k) + "\" has " + rows + " row(s).");
|
||||
for (int r = 0; r < rows; r++) {
|
||||
HSSFRow row = sheet.getRow(r);
|
||||
if (row == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
System.out.println("\nROW " + row.getRowNum() + " has " + row.getPhysicalNumberOfCells() + " cell(s).");
|
||||
for (int c = 0; c < row.getLastCellNum(); c++) {
|
||||
HSSFCell cell = row.getCell(c);
|
||||
String value;
|
||||
System.out.println("\nROW " + row.getRowNum() + " has " + row.getPhysicalNumberOfCells() + " cell(s).");
|
||||
for (int c = 0; c < row.getLastCellNum(); c++) {
|
||||
HSSFCell cell = row.getCell(c);
|
||||
String value;
|
||||
|
||||
if (cell != null) {
|
||||
switch (cell.getCellType()) {
|
||||
if (cell != null) {
|
||||
switch (cell.getCellType()) {
|
||||
|
||||
case FORMULA:
|
||||
value = "FORMULA value=" + cell.getCellFormula();
|
||||
break;
|
||||
case FORMULA:
|
||||
value = "FORMULA value=" + cell.getCellFormula();
|
||||
break;
|
||||
|
||||
case NUMERIC:
|
||||
value = "NUMERIC value=" + cell.getNumericCellValue();
|
||||
break;
|
||||
case NUMERIC:
|
||||
value = "NUMERIC value=" + cell.getNumericCellValue();
|
||||
break;
|
||||
|
||||
case STRING:
|
||||
value = "STRING value=" + cell.getStringCellValue();
|
||||
break;
|
||||
case STRING:
|
||||
value = "STRING value=" + cell.getStringCellValue();
|
||||
break;
|
||||
|
||||
case BLANK:
|
||||
value = "<BLANK>";
|
||||
break;
|
||||
case BLANK:
|
||||
value = "<BLANK>";
|
||||
break;
|
||||
|
||||
case BOOLEAN:
|
||||
value = "BOOLEAN value-" + cell.getBooleanCellValue();
|
||||
break;
|
||||
case BOOLEAN:
|
||||
value = "BOOLEAN value-" + cell.getBooleanCellValue();
|
||||
break;
|
||||
|
||||
case ERROR:
|
||||
value = "ERROR value=" + cell.getErrorCellValue();
|
||||
break;
|
||||
case ERROR:
|
||||
value = "ERROR value=" + cell.getErrorCellValue();
|
||||
break;
|
||||
|
||||
default:
|
||||
value = "UNKNOWN value of type " + cell.getCellType();
|
||||
}
|
||||
System.out.println("CELL col=" + cell.getColumnIndex() + " VALUE=" + value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (args.length == 2) {
|
||||
if ("write".equalsIgnoreCase(args[1])) {
|
||||
System.out.println("Write mode");
|
||||
long time = System.currentTimeMillis();
|
||||
HSSFReadWrite.testCreateSampleSheet(fileName);
|
||||
default:
|
||||
value = "UNKNOWN value of type " + cell.getCellType();
|
||||
}
|
||||
System.out.println("CELL col=" + cell.getColumnIndex() + " VALUE=" + value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (args.length == 2) {
|
||||
if ("write".equalsIgnoreCase(args[1])) {
|
||||
System.out.println("Write mode");
|
||||
long time = System.currentTimeMillis();
|
||||
HSSFReadWrite.testCreateSampleSheet(fileName);
|
||||
|
||||
System.out.println("" + (System.currentTimeMillis() - time) + " ms generation time");
|
||||
} else {
|
||||
System.out.println("readwrite test");
|
||||
try (HSSFWorkbook wb = HSSFReadWrite.readFile(fileName);
|
||||
FileOutputStream stream = new FileOutputStream(args[1])) {
|
||||
wb.write(stream);
|
||||
}
|
||||
}
|
||||
} else if (args.length == 3 && "modify1".equalsIgnoreCase(args[2])) {
|
||||
// delete row 0-24, row 74 - 99 && change cell 3 on row 39 to string "MODIFIED CELL!!"
|
||||
System.out.println("" + (System.currentTimeMillis() - time) + " ms generation time");
|
||||
} else {
|
||||
System.out.println("readwrite test");
|
||||
try (HSSFWorkbook wb = HSSFReadWrite.readFile(fileName);
|
||||
FileOutputStream stream = new FileOutputStream(args[1])) {
|
||||
wb.write(stream);
|
||||
}
|
||||
}
|
||||
} else if (args.length == 3 && "modify1".equalsIgnoreCase(args[2])) {
|
||||
// delete row 0-24, row 74 - 99 && change cell 3 on row 39 to string "MODIFIED CELL!!"
|
||||
|
||||
try (HSSFWorkbook wb = HSSFReadWrite.readFile(fileName);
|
||||
FileOutputStream stream = new FileOutputStream(args[1])) {
|
||||
HSSFSheet sheet = wb.getSheetAt(0);
|
||||
try (HSSFWorkbook wb = HSSFReadWrite.readFile(fileName);
|
||||
FileOutputStream stream = new FileOutputStream(args[1])) {
|
||||
HSSFSheet sheet = wb.getSheetAt(0);
|
||||
|
||||
for (int k = 0; k < 25; k++) {
|
||||
HSSFRow row = sheet.getRow(k);
|
||||
sheet.removeRow(row);
|
||||
}
|
||||
for (int k = 74; k < 100; k++) {
|
||||
HSSFRow row = sheet.getRow(k);
|
||||
sheet.removeRow(row);
|
||||
}
|
||||
HSSFRow row = sheet.getRow(39);
|
||||
HSSFCell cell = row.getCell(3);
|
||||
cell.setCellValue("MODIFIED CELL!!!!!");
|
||||
for (int k = 0; k < 25; k++) {
|
||||
HSSFRow row = sheet.getRow(k);
|
||||
sheet.removeRow(row);
|
||||
}
|
||||
for (int k = 74; k < 100; k++) {
|
||||
HSSFRow row = sheet.getRow(k);
|
||||
sheet.removeRow(row);
|
||||
}
|
||||
HSSFRow row = sheet.getRow(39);
|
||||
HSSFCell cell = row.getCell(3);
|
||||
cell.setCellValue("MODIFIED CELL!!!!!");
|
||||
|
||||
wb.write(stream);
|
||||
}
|
||||
}
|
||||
}
|
||||
wb.write(stream);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -30,7 +30,7 @@ import org.apache.poi.hssf.usermodel.HSSFWorkbook;
|
|||
*/
|
||||
public class HyperlinkFormula {
|
||||
public static void main(String[] args) throws IOException {
|
||||
try (HSSFWorkbook wb = new HSSFWorkbook()) {
|
||||
try (HSSFWorkbook wb = new HSSFWorkbook()) {
|
||||
HSSFSheet sheet = wb.createSheet("new sheet");
|
||||
HSSFRow row = sheet.createRow(0);
|
||||
|
||||
|
|
|
@ -33,25 +33,25 @@ import org.apache.poi.hssf.usermodel.HSSFWorkbook;
|
|||
public class NewLinesInCells {
|
||||
public static void main( String[] args ) throws IOException {
|
||||
try (HSSFWorkbook wb = new HSSFWorkbook()) {
|
||||
HSSFSheet s = wb.createSheet();
|
||||
HSSFFont f2 = wb.createFont();
|
||||
HSSFSheet s = wb.createSheet();
|
||||
HSSFFont f2 = wb.createFont();
|
||||
|
||||
HSSFCellStyle cs = wb.createCellStyle();
|
||||
HSSFCellStyle cs = wb.createCellStyle();
|
||||
|
||||
cs.setFont(f2);
|
||||
// Word Wrap MUST be turned on
|
||||
cs.setWrapText(true);
|
||||
cs.setFont(f2);
|
||||
// Word Wrap MUST be turned on
|
||||
cs.setWrapText(true);
|
||||
|
||||
HSSFRow r = s.createRow(2);
|
||||
r.setHeight((short) 0x349);
|
||||
HSSFCell c = r.createCell(2);
|
||||
c.setCellValue("Use \n with word wrap on to create a new line");
|
||||
c.setCellStyle(cs);
|
||||
s.setColumnWidth(2, (int) ((50 * 8) / ((double) 1 / 20)));
|
||||
HSSFRow r = s.createRow(2);
|
||||
r.setHeight((short) 0x349);
|
||||
HSSFCell c = r.createCell(2);
|
||||
c.setCellValue("Use \n with word wrap on to create a new line");
|
||||
c.setCellStyle(cs);
|
||||
s.setColumnWidth(2, (int) ((50 * 8) / ((double) 1 / 20)));
|
||||
|
||||
try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
|
||||
wb.write(fileOut);
|
||||
}
|
||||
}
|
||||
try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
|
||||
wb.write(fileOut);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -388,16 +388,16 @@ public class AddDimensionedImage {
|
|||
// to the method, the images type is identified before it is added to the
|
||||
// sheet.
|
||||
String sURL = imageFile.toString().toLowerCase(Locale.ROOT);
|
||||
if( sURL.endsWith(".png") ) {
|
||||
if( sURL.endsWith(".png") ) {
|
||||
imageType = Workbook.PICTURE_TYPE_PNG;
|
||||
}
|
||||
else if( sURL.endsWith(".jpg") || sURL.endsWith(".jpeg") ) {
|
||||
}
|
||||
else if( sURL.endsWith(".jpg") || sURL.endsWith(".jpeg") ) {
|
||||
imageType = Workbook.PICTURE_TYPE_JPEG;
|
||||
}
|
||||
else {
|
||||
}
|
||||
else {
|
||||
throw new IllegalArgumentException("Invalid Image file : " +
|
||||
sURL);
|
||||
}
|
||||
}
|
||||
int index = sheet.getWorkbook().addPicture(
|
||||
IOUtils.toByteArray(imageFile.openStream()), imageType);
|
||||
drawing.createPicture(anchor, index);
|
||||
|
@ -818,9 +818,9 @@ public class AddDimensionedImage {
|
|||
*/
|
||||
public static void main(String[] args) throws IOException {
|
||||
if(args.length < 2){
|
||||
System.err.println("Usage: AddDimensionedImage imageFile outputFile");
|
||||
return;
|
||||
}
|
||||
System.err.println("Usage: AddDimensionedImage imageFile outputFile");
|
||||
return;
|
||||
}
|
||||
|
||||
final String imageFile = args[0];
|
||||
final String outputFile = args[1];
|
||||
|
|
|
@ -45,7 +45,7 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
|||
@SuppressWarnings({"java:S106","java:S4823","java:S1192"})
|
||||
public final class TimesheetDemo {
|
||||
private static final String[] titles = {
|
||||
"Person", "ID", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun",
|
||||
"Person", "ID", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun",
|
||||
"Total\nHrs", "Overtime\nHrs", "Regular\nHrs"
|
||||
};
|
||||
|
||||
|
|
|
@ -76,42 +76,42 @@ public final class PieChartDemo {
|
|||
}
|
||||
}
|
||||
|
||||
if(chart == null) {
|
||||
throw new IllegalStateException("chart not found in the template");
|
||||
}
|
||||
if(chart == null) {
|
||||
throw new IllegalStateException("chart not found in the template");
|
||||
}
|
||||
|
||||
// Series Text
|
||||
List<XDDFChartData> series = chart.getChartSeries();
|
||||
XDDFPieChartData pie = (XDDFPieChartData) series.get(0);
|
||||
// Series Text
|
||||
List<XDDFChartData> series = chart.getChartSeries();
|
||||
XDDFPieChartData pie = (XDDFPieChartData) series.get(0);
|
||||
|
||||
// Category Axis Data
|
||||
List<String> listCategories = new ArrayList<>(3);
|
||||
// Category Axis Data
|
||||
List<String> listCategories = new ArrayList<>(3);
|
||||
|
||||
// Values
|
||||
List<Double> listValues = new ArrayList<>(3);
|
||||
// Values
|
||||
List<Double> listValues = new ArrayList<>(3);
|
||||
|
||||
// set model
|
||||
String ln;
|
||||
while((ln = modelReader.readLine()) != null){
|
||||
String[] vals = ln.split("\\s+");
|
||||
listCategories.add(vals[0]);
|
||||
listValues.add(Double.valueOf(vals[1]));
|
||||
}
|
||||
String[] categories = listCategories.toArray(new String[0]);
|
||||
Double[] values = listValues.toArray(new Double[0]);
|
||||
// set model
|
||||
String ln;
|
||||
while((ln = modelReader.readLine()) != null){
|
||||
String[] vals = ln.split("\\s+");
|
||||
listCategories.add(vals[0]);
|
||||
listValues.add(Double.valueOf(vals[1]));
|
||||
}
|
||||
String[] categories = listCategories.toArray(new String[0]);
|
||||
Double[] values = listValues.toArray(new Double[0]);
|
||||
|
||||
final int numOfPoints = categories.length;
|
||||
final String categoryDataRange = chart.formatRange(new CellRangeAddress(1, numOfPoints, 0, 0));
|
||||
final String valuesDataRange = chart.formatRange(new CellRangeAddress(1, numOfPoints, 1, 1));
|
||||
final XDDFDataSource<?> categoriesData = XDDFDataSourcesFactory.fromArray(categories, categoryDataRange);
|
||||
final XDDFNumericalDataSource<? extends Number> valuesData = XDDFDataSourcesFactory.fromArray(values, valuesDataRange);
|
||||
final int numOfPoints = categories.length;
|
||||
final String categoryDataRange = chart.formatRange(new CellRangeAddress(1, numOfPoints, 0, 0));
|
||||
final String valuesDataRange = chart.formatRange(new CellRangeAddress(1, numOfPoints, 1, 1));
|
||||
final XDDFDataSource<?> categoriesData = XDDFDataSourcesFactory.fromArray(categories, categoryDataRange);
|
||||
final XDDFNumericalDataSource<? extends Number> valuesData = XDDFDataSourcesFactory.fromArray(values, valuesDataRange);
|
||||
|
||||
XDDFPieChartData.Series firstSeries = (XDDFPieChartData.Series) pie.getSeries(0);
|
||||
firstSeries.replaceData(categoriesData, valuesData);
|
||||
firstSeries.setTitle(chartTitle, chart.setSheetTitle(chartTitle, 0));
|
||||
firstSeries.setExplosion(25L);
|
||||
firstSeries.getDataPoint(1).setExplosion(35L);
|
||||
chart.plot(pie);
|
||||
XDDFPieChartData.Series firstSeries = (XDDFPieChartData.Series) pie.getSeries(0);
|
||||
firstSeries.replaceData(categoriesData, valuesData);
|
||||
firstSeries.setTitle(chartTitle, chart.setSheetTitle(chartTitle, 0));
|
||||
firstSeries.setExplosion(25L);
|
||||
firstSeries.getDataPoint(1).setExplosion(35L);
|
||||
chart.plot(pie);
|
||||
|
||||
// save the result
|
||||
try (OutputStream out = new FileOutputStream("pie-chart-demo-output.pptx")) {
|
||||
|
|
|
@ -51,9 +51,9 @@ public class FromHowTo {
|
|||
|
||||
// process the first sheet
|
||||
try (InputStream sheet = r.getSheetsData().next()) {
|
||||
InputSource sheetSource = new InputSource(sheet);
|
||||
parser.parse(sheetSource);
|
||||
}
|
||||
InputSource sheetSource = new InputSource(sheet);
|
||||
parser.parse(sheetSource);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -68,9 +68,9 @@ public class FromHowTo {
|
|||
while (sheets.hasNext()) {
|
||||
System.out.println("Processing new sheet:\n");
|
||||
try (InputStream sheet = sheets.next()) {
|
||||
InputSource sheetSource = new InputSource(sheet);
|
||||
parser.parse(sheetSource);
|
||||
}
|
||||
InputSource sheetSource = new InputSource(sheet);
|
||||
parser.parse(sheetSource);
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -101,5 +101,5 @@ public class HeaderFooterTable {
|
|||
doc.write(os);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -30,36 +30,36 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText;
|
|||
|
||||
public class SimpleDocumentWithHeader {
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
try (XWPFDocument doc = new XWPFDocument()) {
|
||||
public static void main(String[] args) throws IOException {
|
||||
try (XWPFDocument doc = new XWPFDocument()) {
|
||||
|
||||
XWPFParagraph p = doc.createParagraph();
|
||||
XWPFParagraph p = doc.createParagraph();
|
||||
|
||||
XWPFRun r = p.createRun();
|
||||
r.setText("Some Text");
|
||||
r.setBold(true);
|
||||
r = p.createRun();
|
||||
r.setText("Goodbye");
|
||||
XWPFRun r = p.createRun();
|
||||
r.setText("Some Text");
|
||||
r.setBold(true);
|
||||
r = p.createRun();
|
||||
r.setText("Goodbye");
|
||||
|
||||
CTP ctP = CTP.Factory.newInstance();
|
||||
CTText t = ctP.addNewR().addNewT();
|
||||
t.setStringValue("header");
|
||||
XWPFParagraph[] pars = new XWPFParagraph[1];
|
||||
p = new XWPFParagraph(ctP, doc);
|
||||
pars[0] = p;
|
||||
CTP ctP = CTP.Factory.newInstance();
|
||||
CTText t = ctP.addNewR().addNewT();
|
||||
t.setStringValue("header");
|
||||
XWPFParagraph[] pars = new XWPFParagraph[1];
|
||||
p = new XWPFParagraph(ctP, doc);
|
||||
pars[0] = p;
|
||||
|
||||
XWPFHeaderFooterPolicy hfPolicy = doc.createHeaderFooterPolicy();
|
||||
hfPolicy.createHeader(XWPFHeaderFooterPolicy.DEFAULT, pars);
|
||||
XWPFHeaderFooterPolicy hfPolicy = doc.createHeaderFooterPolicy();
|
||||
hfPolicy.createHeader(XWPFHeaderFooterPolicy.DEFAULT, pars);
|
||||
|
||||
ctP = CTP.Factory.newInstance();
|
||||
t = ctP.addNewR().addNewT();
|
||||
t.setStringValue("My Footer");
|
||||
pars[0] = new XWPFParagraph(ctP, doc);
|
||||
hfPolicy.createFooter(XWPFHeaderFooterPolicy.DEFAULT, pars);
|
||||
ctP = CTP.Factory.newInstance();
|
||||
t = ctP.addNewR().addNewT();
|
||||
t.setStringValue("My Footer");
|
||||
pars[0] = new XWPFParagraph(ctP, doc);
|
||||
hfPolicy.createFooter(XWPFHeaderFooterPolicy.DEFAULT, pars);
|
||||
|
||||
try (OutputStream os = new FileOutputStream(new File("header.docx"))) {
|
||||
doc.write(os);
|
||||
}
|
||||
}
|
||||
}
|
||||
try (OutputStream os = new FileOutputStream(new File("header.docx"))) {
|
||||
doc.write(os);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -49,20 +49,20 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalJc;
|
|||
public class SimpleTable {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
try {
|
||||
createSimpleTable();
|
||||
}
|
||||
catch(Exception e) {
|
||||
System.out.println("Error trying to create simple table.");
|
||||
throw(e);
|
||||
}
|
||||
try {
|
||||
createStyledTable();
|
||||
}
|
||||
catch(Exception e) {
|
||||
System.out.println("Error trying to create styled table.");
|
||||
throw(e);
|
||||
}
|
||||
try {
|
||||
createSimpleTable();
|
||||
}
|
||||
catch(Exception e) {
|
||||
System.out.println("Error trying to create simple table.");
|
||||
throw(e);
|
||||
}
|
||||
try {
|
||||
createStyledTable();
|
||||
}
|
||||
catch(Exception e) {
|
||||
System.out.println("Error trying to create styled table.");
|
||||
throw(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void createSimpleTable() throws Exception {
|
||||
|
@ -107,7 +107,7 @@ public class SimpleTable {
|
|||
* instructive and give you ideas for your own solutions.
|
||||
*/
|
||||
public static void createStyledTable() throws Exception {
|
||||
// Create a new document from scratch
|
||||
// Create a new document from scratch
|
||||
|
||||
try (XWPFDocument doc = new XWPFDocument()) {
|
||||
// -- OR --
|
||||
|
|
|
@ -28,7 +28,7 @@ import java.io.IOException;
|
|||
|
||||
public class RubyOutputStream extends OutputStream {
|
||||
|
||||
//pointer to native ruby VALUE
|
||||
//pointer to native ruby VALUE
|
||||
protected long rubyIO;
|
||||
|
||||
public RubyOutputStream (long rubyIO)
|
||||
|
@ -38,7 +38,7 @@ public class RubyOutputStream extends OutputStream {
|
|||
}
|
||||
|
||||
@Override
|
||||
protected void finalize()
|
||||
protected void finalize()
|
||||
throws Throwable
|
||||
{
|
||||
// decRef();
|
||||
|
@ -48,14 +48,14 @@ public class RubyOutputStream extends OutputStream {
|
|||
// protected native void decRef();
|
||||
|
||||
@Override
|
||||
public native void close()
|
||||
public native void close()
|
||||
throws IOException;
|
||||
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see java.io.OutputStream#write(int)
|
||||
*/
|
||||
@Override
|
||||
public native void write(int arg0) throws IOException;
|
||||
/* (non-Javadoc)
|
||||
* @see java.io.OutputStream#write(int)
|
||||
*/
|
||||
@Override
|
||||
public native void write(int arg0) throws IOException;
|
||||
}
|
||||
|
||||
|
|
|
@ -34,82 +34,82 @@ import org.junit.jupiter.api.BeforeEach;
|
|||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class TestXLSX2CSV {
|
||||
private PrintStream err;
|
||||
private final UnsynchronizedByteArrayOutputStream errorBytes = new UnsynchronizedByteArrayOutputStream();
|
||||
private PrintStream err;
|
||||
private final UnsynchronizedByteArrayOutputStream errorBytes = new UnsynchronizedByteArrayOutputStream();
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() throws UnsupportedEncodingException {
|
||||
// remember and replace default error streams
|
||||
err = System.err;
|
||||
@BeforeEach
|
||||
public void setUp() throws UnsupportedEncodingException {
|
||||
// remember and replace default error streams
|
||||
err = System.err;
|
||||
|
||||
PrintStream error = new PrintStream(errorBytes, true, "UTF-8");
|
||||
System.setErr(error);
|
||||
}
|
||||
PrintStream error = new PrintStream(errorBytes, true, "UTF-8");
|
||||
System.setErr(error);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
public void tearDown() {
|
||||
// restore output-streams again
|
||||
System.setErr(err);
|
||||
@AfterEach
|
||||
public void tearDown() {
|
||||
// restore output-streams again
|
||||
System.setErr(err);
|
||||
|
||||
// Print out found error
|
||||
if (errorBytes.size() > 0) {
|
||||
System.err.println("Had stderr: " + errorBytes.toString(StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
// Print out found error
|
||||
if (errorBytes.size() > 0) {
|
||||
System.err.println("Had stderr: " + errorBytes.toString(StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNoArgument() throws Exception {
|
||||
// returns with some System.err
|
||||
XLSX2CSV.main(new String[0]);
|
||||
@Test
|
||||
public void testNoArgument() throws Exception {
|
||||
// returns with some System.err
|
||||
XLSX2CSV.main(new String[0]);
|
||||
|
||||
String output = errorBytes.toString(StandardCharsets.UTF_8);
|
||||
assertTrue(output.contains("XLSX2CSV <xlsx file>"), "Had: " + output);
|
||||
}
|
||||
String output = errorBytes.toString(StandardCharsets.UTF_8);
|
||||
assertTrue(output.contains("XLSX2CSV <xlsx file>"), "Had: " + output);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInvalidFile() throws Exception {
|
||||
// returns with some System.err
|
||||
XLSX2CSV.main(new String[] { "not-existing-file.xlsx" });
|
||||
@Test
|
||||
public void testInvalidFile() throws Exception {
|
||||
// returns with some System.err
|
||||
XLSX2CSV.main(new String[] { "not-existing-file.xlsx" });
|
||||
|
||||
String output = errorBytes.toString("UTF-8");
|
||||
assertTrue(output.contains("Not found or not a file: not-existing-file.xlsx"), "Had: " + output);
|
||||
}
|
||||
String output = errorBytes.toString("UTF-8");
|
||||
assertTrue(output.contains("Not found or not a file: not-existing-file.xlsx"), "Had: " + output);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSampleFile() throws Exception {
|
||||
final UnsynchronizedByteArrayOutputStream outputBytes = new UnsynchronizedByteArrayOutputStream();
|
||||
PrintStream out = new PrintStream(outputBytes, true, "UTF-8");
|
||||
@Test
|
||||
public void testSampleFile() throws Exception {
|
||||
final UnsynchronizedByteArrayOutputStream outputBytes = new UnsynchronizedByteArrayOutputStream();
|
||||
PrintStream out = new PrintStream(outputBytes, true, "UTF-8");
|
||||
|
||||
// The package open is instantaneous, as it should be.
|
||||
try (OPCPackage p = OPCPackage.open(XSSFTestDataSamples.getSampleFile("sample.xlsx").getAbsolutePath(), PackageAccess.READ)) {
|
||||
XLSX2CSV xlsx2csv = new XLSX2CSV(p, out, -1);
|
||||
xlsx2csv.process();
|
||||
}
|
||||
// The package open is instantaneous, as it should be.
|
||||
try (OPCPackage p = OPCPackage.open(XSSFTestDataSamples.getSampleFile("sample.xlsx").getAbsolutePath(), PackageAccess.READ)) {
|
||||
XLSX2CSV xlsx2csv = new XLSX2CSV(p, out, -1);
|
||||
xlsx2csv.process();
|
||||
}
|
||||
|
||||
String errorOutput = errorBytes.toString(StandardCharsets.UTF_8);
|
||||
assertEquals(errorOutput.length(), 0);
|
||||
String errorOutput = errorBytes.toString(StandardCharsets.UTF_8);
|
||||
assertEquals(errorOutput.length(), 0);
|
||||
|
||||
String output = outputBytes.toString(StandardCharsets.UTF_8);
|
||||
assertTrue(output.contains("\"Lorem\",111"), "Had: " + output);
|
||||
assertTrue(output.contains(",\"hello, xssf\",,\"hello, xssf\""), "Had: " + output);
|
||||
}
|
||||
String output = outputBytes.toString(StandardCharsets.UTF_8);
|
||||
assertTrue(output.contains("\"Lorem\",111"), "Had: " + output);
|
||||
assertTrue(output.contains(",\"hello, xssf\",,\"hello, xssf\""), "Had: " + output);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMinColumns() throws Exception {
|
||||
final UnsynchronizedByteArrayOutputStream outputBytes = new UnsynchronizedByteArrayOutputStream();
|
||||
PrintStream out = new PrintStream(outputBytes, true, "UTF-8");
|
||||
@Test
|
||||
public void testMinColumns() throws Exception {
|
||||
final UnsynchronizedByteArrayOutputStream outputBytes = new UnsynchronizedByteArrayOutputStream();
|
||||
PrintStream out = new PrintStream(outputBytes, true, "UTF-8");
|
||||
|
||||
// The package open is instantaneous, as it should be.
|
||||
try (OPCPackage p = OPCPackage.open(XSSFTestDataSamples.getSampleFile("sample.xlsx").getAbsolutePath(), PackageAccess.READ)) {
|
||||
XLSX2CSV xlsx2csv = new XLSX2CSV(p, out, 5);
|
||||
xlsx2csv.process();
|
||||
}
|
||||
// The package open is instantaneous, as it should be.
|
||||
try (OPCPackage p = OPCPackage.open(XSSFTestDataSamples.getSampleFile("sample.xlsx").getAbsolutePath(), PackageAccess.READ)) {
|
||||
XLSX2CSV xlsx2csv = new XLSX2CSV(p, out, 5);
|
||||
xlsx2csv.process();
|
||||
}
|
||||
|
||||
String errorOutput = errorBytes.toString(StandardCharsets.UTF_8);
|
||||
assertEquals(errorOutput.length(), 0);
|
||||
String errorOutput = errorBytes.toString(StandardCharsets.UTF_8);
|
||||
assertEquals(errorOutput.length(), 0);
|
||||
|
||||
String output = outputBytes.toString(StandardCharsets.UTF_8);
|
||||
assertTrue(output.contains("\"Lorem\",111,,,"), "Had: " + output);
|
||||
assertTrue(output.contains(",\"hello, xssf\",,\"hello, xssf\","), "Had: " + output);
|
||||
}
|
||||
String output = outputBytes.toString(StandardCharsets.UTF_8);
|
||||
assertTrue(output.contains("\"Lorem\",111,,,"), "Had: " + output);
|
||||
assertTrue(output.contains(",\"hello, xssf\",,\"hello, xssf\","), "Had: " + output);
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue