Example usage for org.apache.poi.openxml4j.opc OPCPackage open

List of usage examples for org.apache.poi.openxml4j.opc OPCPackage open

Introduction

In this page you can find the example usage for org.apache.poi.openxml4j.opc OPCPackage open.

Prototype

public static OPCPackage open(File file, PackageAccess access) throws InvalidFormatException 

Source Link

Document

Open a package.

Usage

From source file:XLSX2CSV.java

License:Apache License

public XLSX2CSV(String inputFilePath, String outputFilePath) throws Exception {
    xlsxPackage = OPCPackage.open(inputFilePath, PackageAccess.READ);
    output = new PrintStream(outputFilePath, OUTPUT_CHARSET);
    minColumns = -1;/*from   w  ww . j ava  2 s .  c o  m*/
}

From source file:adams.data.io.input.ExcelStreamingSpreadSheetReader.java

License:Open Source License

/**
 * Determines the number of sheets in the file.
 * /*from  w w  w.jav  a  2s  .co m*/
 * @param file   the file to inspec
 * @return      the number of sheets
 * @throws Exception   if reading of file fails
 */
protected int getSheetCount(File file) throws Exception {
    int result;
    OPCPackage pkg;
    XSSFReader reader;
    Iterator<InputStream> sheets;
    InputStream sheet;

    pkg = OPCPackage.open(file.getAbsolutePath(), PackageAccess.READ);
    reader = new XSSFReader(pkg);
    sheets = reader.getSheetsData();
    result = 0;
    while (sheets.hasNext()) {
        if (m_Stopped)
            break;
        sheet = sheets.next();
        sheet.close();
        result++;
    }
    pkg.close();

    return result;
}

From source file:adams.data.io.input.ExcelStreamingSpreadSheetReader.java

License:Open Source License

/**
 * Reads the spreadsheet content from the specified file.
 *
 * @param file   the file to read from/*from  w ww  .j  a va 2 s  . c o  m*/
 * @return      the spreadsheets or null in case of an error
 */
@Override
protected List<SpreadSheet> doReadRange(File file) {
    List<SpreadSheet> result;
    int count;
    OPCPackage pkg;
    XSSFReader reader;
    SharedStringsTable sst;
    XMLReader parser;
    XSSFReader.SheetIterator sheets;
    InputStream sheet;
    SpreadSheet spsheet;
    InputSource sheetSource;
    HashSet<Integer> indices;
    List<String> header;
    Row rowOld;
    Row row;
    int i;

    result = new ArrayList<>();

    try {
        m_SheetRange.setMax(getSheetCount(file));
        indices = new HashSet<>(Utils.toList(m_SheetRange.getIntIndices()));
        pkg = OPCPackage.open(file.getAbsolutePath(), PackageAccess.READ);
        reader = new XSSFReader(pkg);
        sst = reader.getSharedStringsTable();
        sheets = (XSSFReader.SheetIterator) reader.getSheetsData();
        count = 0;
        while (sheets.hasNext()) {
            if (m_Stopped)
                break;
            sheet = null;
            try {
                sheet = sheets.next();
                if (indices.contains(count)) {
                    spsheet = m_SpreadSheetType.newInstance();
                    spsheet.setDataRowClass(m_DataRowType.getClass());
                    spsheet.setName(sheets.getSheetName());
                    parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
                    m_Handler = new SheetHandler(this, spsheet, sst);
                    parser.setContentHandler(m_Handler);
                    sheetSource = new InputSource(sheet);
                    parser.parse(sheetSource);
                    // fix header?
                    if (!getCustomColumnHeaders().trim().isEmpty()) {
                        header = SpreadSheetUtils.createHeader(spsheet.getColumnCount(),
                                getCustomColumnHeaders());
                        row = spsheet.getHeaderRow();
                        for (i = 0; i < header.size() && i < spsheet.getColumnCount(); i++)
                            row.getCell(i).setContent(header.get(i));
                    }
                    result.add(spsheet);
                    // missing types?
                    if (m_Handler.getUnknownCellTypes().size() > 0) {
                        getLogger().severe("Unknown cell types: " + m_Handler.getUnknownCellTypes());
                        for (String type : m_Handler.getUnknownCellTypes())
                            getLogger().severe("- cell type '" + type + "': "
                                    + m_Handler.getUnknownCellTypesExamples().get(type));
                    }
                    if (m_Handler.getUnknownCellStrings().size() > 0) {
                        getLogger().severe("Unknown cell strings: " + m_Handler.getUnknownCellStrings());
                        for (String str : m_Handler.getUnknownCellStrings())
                            getLogger().severe("- cell string '" + str + "': "
                                    + m_Handler.getUnknownCellStringsExamples().get(str));
                    }
                }
            } catch (Exception e) {
                getLogger().log(Level.SEVERE, "Failed to process sheet:", e);
            }

            FileUtils.closeQuietly(sheet);

            count++;
        }
        pkg.close();
    } catch (ParseStopException e) {
        getLogger().severe("Parsing stopped!");
        result = null;
        m_LastError = "Failed to read range '" + m_SheetRange + "' from file '" + file + "'!\n"
                + Utils.throwableToString(e);
    } catch (Exception e) {
        getLogger().log(Level.SEVERE, "Failed to read spreadsheet:", e);
    }

    m_Handler = null;

    return result;
}

From source file:br.com.mapfre.lv.jobmanager.XLSX2CSV.java

License:Apache License

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

    //FileOutputStream fos =new FileOutputStream("xmlPlanilha.xml");

    File xlsxFile = new File("planilhaTeste.xlsx.zip");
    if (!xlsxFile.exists()) {
        System.err.println("Not found or not a file: " + xlsxFile.getPath());
        return;//from  www .j a v  a2 s  .  co m
    }

    int minColumns = -1;
    if (args.length >= 2)
        minColumns = Integer.parseInt(args[1]);

    // The package open is instantaneous, as it should be.
    OPCPackage p = OPCPackage.open(xlsxFile.getPath(), PackageAccess.READ);
    XLSX2CSV xlsx2csv = new XLSX2CSV(p, System.out, minColumns);
    xlsx2csv.process();
}

From source file:ch.admin.searchreplace.SearchReplaceTerms.java

License:Apache License

private static HashMap<String, String> readSearchReplaceTerms(String input) throws Exception {
    HashMap<String, String> terms = new HashMap<String, String>();

    // The package open is instantaneous, as it should be.
    OPCPackage xlsxPackage = OPCPackage.open(input, PackageAccess.READ);
    ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(xlsxPackage);
    XSSFReader xssfReader = new XSSFReader(xlsxPackage);
    StylesTable styles = xssfReader.getStylesTable();
    XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData();

    InputStream stream = iter.next();
    String sheetName = iter.getSheetName();
    System.out.println(sheetName);

    InputSource sheetSource = new InputSource(stream);
    SAXParserFactory saxFactory = SAXParserFactory.newInstance();
    SAXParser saxParser = saxFactory.newSAXParser();
    XMLReader sheetParser = saxParser.getXMLReader();
    ContentHandler handler = new MyXSSFSheetHandler(styles, strings, terms);
    sheetParser.setContentHandler(handler);
    sheetParser.parse(sheetSource);//  w  w  w. ja  v a  2 s. c  om

    stream.close();

    return (terms);

}

From source file:ch.admin.searchreplace.XLSX2CSV.java

License:Apache License

public static void main(String[] args) throws Exception {
    if (args.length < 1) {
        System.err.println("Use:");
        System.err.println("  XLSX2CSV <xlsx file> [min columns]");
        return;/*from   www . j a va 2 s .  com*/
    }

    File xlsxFile = new File(args[0]);
    if (!xlsxFile.exists()) {
        System.err.println("Not found or not a file: " + xlsxFile.getPath());
        return;
    }

    int minColumns = -1;
    if (args.length >= 2)
        minColumns = Integer.parseInt(args[1]);

    // The package open is instantaneous, as it should be.
    OPCPackage p = OPCPackage.open(xlsxFile.getPath(), PackageAccess.READ);
    XLSX2CSV xlsx2csv = new XLSX2CSV(p, System.out, minColumns);
    xlsx2csv.process();
}

From source file:cn.sinobest.jzpt.minidemo.poidemo.example.XLSX2CSV.java

License:Apache License

public static void main(String[] args) throws Exception {
    //        if (args.length < 1) {
    //            System.err.println("Use:");
    //            System.err.println("  XLSX2CSV <xlsx file> [min columns]");
    //            return;
    //        }// w w w  .  j  a v  a  2  s . c o  m

    //        File xlsxFile = new File(args[0]);
    File xlsxFile = new File("c:\\1.xlsx");
    if (!xlsxFile.exists()) {
        System.err.println("Not found or not a file: " + xlsxFile.getPath());
        return;
    }

    int minColumns = -1;
    if (args.length >= 2)
        minColumns = Integer.parseInt(args[1]);

    // The package open is instantaneous, as it should be.
    OPCPackage p = OPCPackage.open(xlsxFile.getPath(), PackageAccess.READ);
    XLSX2CSV xlsx2csv = new XLSX2CSV(p, System.out, minColumns);
    xlsx2csv.process();
}

From source file:cn.xiaozhi.spider.util.XLSXCovertCSVReader.java

License:Apache License

/**
 * ?Excel//from   www.  j av  a  2  s. co  m
 *
 * @param path
 *            
 * @param sheetName
 *            sheet??
 * @param minColumns
 *            
 * @return
 * @throws SAXException
 * @throws ParserConfigurationException
 * @throws OpenXML4JException
 * @throws IOException
 */
private static List<String[]> readerExcel(String path, String sheetName, int minColumns)
        throws IOException, OpenXML4JException, ParserConfigurationException, SAXException {
    OPCPackage p = OPCPackage.open(path, PackageAccess.READ);
    XLSXCovertCSVReader xlsx2csv = new XLSXCovertCSVReader(p, System.out, sheetName, minColumns);
    List<String[]> list = xlsx2csv.process();
    p.close();
    return list;
}

From source file:com.catdog.common.util.ExcelReadAndWrite.java

License:Apache License

/**
 * ?Excel/* w ww.  j a v a  2 s  . c  om*/
 * 
 * @param path
 *            
 * @param sheetName
 *            sheet??
 * @param minColumns
 *            
 * @return
 * @throws SAXException
 * @throws ParserConfigurationException
 * @throws OpenXML4JException
 * @throws IOException
 */
public static List<String[]> readerExcel(String path, String sheetName, int minColumns)
        throws IOException, OpenXML4JException, ParserConfigurationException, SAXException {
    OPCPackage p = OPCPackage.open(path, PackageAccess.READ);
    ExcelReadAndWrite xlsx2csv = new ExcelReadAndWrite(p, System.out, sheetName, minColumns);
    List<String[]> list = xlsx2csv.process();
    p.close();
    return list;
}

From source file:com.common.util.MaterialImportExcel2CVS.java

License:Apache License

/**
 * ?Excel/* www .  j  a  v a 2 s  . c  om*/
 * 
 * @param path
 *            
 * @param sheetName
 *            sheet??
 * @param minColumns
 *            
 * @return
 * @throws SAXException
 * @throws ParserConfigurationException
 * @throws OpenXML4JException
 * @throws IOException
 */
private static List<String[]> readerExcel(String path, String sheetName, int minColumns)
        throws IOException, OpenXML4JException, ParserConfigurationException, SAXException {
    OPCPackage p = OPCPackage.open(path, PackageAccess.READ);
    MaterialImportExcel2CVS xlsx2csv = new MaterialImportExcel2CVS(p, System.out, sheetName, minColumns);
    List<String[]> list = xlsx2csv.process();
    p.close();
    return list;
}