导出list对象到excel

@param list     导出的list
@param xmlPath  xml完整路径
@param outputStream 输出流
@return 处理结果，true成功，false失败
@throws Exception
436967
public static boolean list2Xls(List<?> list, String xmlPath, OutputStream outputStream) throws Exception {
        try {
            ExcelConfig config = getEasyExcel(xmlPath);
            return list2Xls(config, list, outputStream);
        } catch (Exception e1) {
            return false;
        }
    }
695228
protected XMLStreamWriter createStreamWriter(OutputStream output) throws XMLStreamException {
        if (outputFactory == null) {
            outputFactory = XMLOutputFactory.newInstance();
        }
        return outputFactory.createXMLStreamWriter(output);
    }
259199
public static OutputStream toFile(String filepath) throws FileNotFoundException {
		if(Strings.isValid(filepath)) {
			return new FileOutputStream(new File(filepath));
		}
		return null;
	}
778934
public static boolean list2Xls(List<?> list, String xmlPath, String filePath, String fileName) throws Exception {
        //创建目录
        File file = new File(filePath);
        if (!(file.exists())) {
            if (!file.mkdirs()) {
                throw new RuntimeException("创建导出目录失败!");
            }
        }
        try {
            ExcelConfig config = getEasyExcel(xmlPath);
            return list2Xls(config, list, filePath, fileName);
        } catch (Exception e1) {
            return false;
        }
    }
847337
public void generateXls(OutputStream out, List<Map<String, Object>> rows, List<ColumnDef> columns) {
        try {
            Workbook wb = new HSSFWorkbook();  // or new XSSFWorkbook();
            String safeName = WorkbookUtil.createSafeSheetName("Report"); // returns " O'Brien's sales   "
            Sheet reportSheet = wb.createSheet(safeName);

            short rowc = 0;
            Row nrow = reportSheet.createRow(rowc++);
            short cellc = 0;
            if (rows == null) return;
            if (columns == null && rows.size() > 0)
            {
                columns = new ArrayList<ColumnDef>(CollectionUtils.collect(rows.get(0).keySet(), new Transformer() {
                    @Override
                    public Object transform(final Object input) {
                        return new ColumnDef()
                        {{
                                setName((String)input);
                            }};
                    }
                }));
            }
            if (columns != null)
            {
                for (ColumnDef column : columns)
                {
                    Cell cell = nrow.createCell(cellc++);
                    cell.setCellValue(column.getName());
                }
            }
            for (Map<String, Object> row : rows)
            {
                nrow = reportSheet.createRow(rowc++);
                cellc = 0;
                for (ColumnDef column : columns)
                {
                    Cell cell = nrow.createCell(cellc++);
                    cell.setCellValue(String.valueOf(row.get(column.getName())));
                }
            }
            wb.write(out);
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

    }
1153596
static Set<User> brokeUserList(final String dataFilePath)
    {
        Set<User> users = new HashSet<User>();
        Workbook workBook = null;
        File file = new File(dataFilePath);
        InputStream excelDocumentStream = null;
        try
        {
            excelDocumentStream = new FileInputStream(file);
            POIFSFileSystem fsPOI = new POIFSFileSystem(new BufferedInputStream(excelDocumentStream));
            workBook = new HSSFWorkbook(fsPOI);
            UserBroker parser = new UserBroker(workBook.getSheetAt(0));
            User user;
            while ((user = parser.addUser(users)) != null)
            {
                users.add(user);
            }
            excelDocumentStream.close();

        }
        catch (Exception e)
        {
          throw new RuntimeException("Error while processing brokeUserList(), Caused by :",e);
        }
        
        return users;
    }
855588
public static void writeFileList(XMLOutput xmlOutput, String tagName, Iterator<File> listValueIterator) throws IOException {
        while (listValueIterator.hasNext()) {
            xmlOutput.openTag(tagName);
            xmlOutput.writeText(listValueIterator.next().getPath());
            xmlOutput.closeTag(tagName);
        }
    }
1082695
public void exportObjects2Excel(String templatePath, List<?> data, Class clazz, String targetPath)
            throws Excel4JException {

        exportObjects2Excel(templatePath, 0, data, null, clazz, true, targetPath);
    }
160260
static OutputStream toXlsxFile(final IDataSet dataSet, final InputStream formatting) {
        ByteArrayOutputStream xlsx = new ByteArrayOutputStream();
        
        try { toWorkbook(dataSet, ConverterUtils.newWorkbook(formatting)).write(xlsx); }
        catch (IOException e) { throw new CalculationEngineException(e); }
        
        return xlsx;
    }
1372515
public static List<?> xls2List(String xmlPath, InputStream inputStream) throws Exception {
        Workbook wb = null;
        List<?> list = null;
        try {
            wb = Workbook.getWorkbook(inputStream);
            list = workbook2List(xmlPath, wb);
        } catch (Exception e) {
            throw new Exception("转换xls出错:" + e.getMessage());
        } finally {
            if (wb != null) {
                wb.close();
            }
        }
        return list;
    }
273125
public static <T> T fromXml(File xmlPath, Class<T> type) {
        BufferedReader reader = null;
        StringBuilder sb = null;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(xmlPath), ENCODING));
            String line = null;
            sb = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (FileNotFoundException e) {
            throw new IllegalArgumentException(e.getMessage());
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    //ignore
                }
            }
        }
        return fromXml(sb.toString(), type);
    }
205562
public void writeToExcel(List<? extends Object> datas, boolean hasTitle, String path,
                             int inMemory, boolean transverse) throws IOException {
        writeToExcel(datas, hasTitle, new FileOutputStream(path), inMemory, transverse);
    }
189874
@Override
  public String []list(String path) throws IOException
  {
    if (path.startsWith("/")) {
      path = path.substring(1);
    }
    
    if (! path.endsWith("/")) {
      path = path + "/";
    }

    ArrayList<String> names = new ArrayList<>();
    
    try (ZipInputStream zIn = new ZipInputStream(getBacking().openRead())) {
      ZipEntry entry;
      
      while ((entry = zIn.getNextEntry()) != null) {
        String name = entry.getName();

        if (name.startsWith(path)) {
          String tail = name.substring(path.length());
          int p = tail.indexOf('/');
          
          if (p >= 0) {
            tail = tail.substring(0, p);
          }
          
          if (! tail.equals("") && ! names.contains(tail)) {
            names.add(tail);
          }
        }
      }
    }
    
    String []list = new String[names.size()];
    
    names.toArray(list);
    
    return list;
  }
1264172
public static <T> File appendUtf8Lines(Collection<T> list, String path) throws IORuntimeException {
		return appendLines(list, path, CharsetUtil.CHARSET_UTF_8);
	}
1249065
public void exportObjects2CSV(List<?> data, Class clazz, boolean isWriteHeader, OutputStream os)
            throws Excel4JException {

        try {
            Writer writer = new OutputStreamWriter(os);
            exportCSVByMapHandler(data, clazz, isWriteHeader, writer);
        } catch (Excel4JException | IOException e) {
            throw new Excel4JException(e);
        }
    }
805349
public ArrayList<Table> extract(File pdfFile, String outputDirPath) {
	m_docInfo = new DocInfo();
	xml_root = new Element("document");// create the root element:<document
					   // id="x.x.x.x.pdf"></document>
	xml_root.setAttribute("id",
		pdfFile.getName().substring(0, pdfFile.getName().length() - 4));
	Element xml_tables = new Element("tables");
	xml_root.addContent(xml_tables);
	xml_doc = new Document(xml_root); // prepare an empty XML doc with root
					  // <Tables>

	// System.out.printf("extracting tables from %s...\n",
	// pdfFile.getName());

	if (m_parser == null) {
	    System.out.printf("[Error] no parser is set\n");
	    return null;
	} else {
	    /*
	     * step 1: extracts words from the PDF document
	     */
	    ArrayList<ArrayList<TextPiece>> wordsByPage = m_parser
		    .getTextPiecesByPage(pdfFile);
	    tables = new ArrayList<Table>();

	    if (wordsByPage != null && wordsByPage.size() != 0) { // in order to
								  // keep the
								  // fast speed
								  // for large
								  // repositories,
								  // we do not
								  // process PDF
								  // files with
								  // 150+ pages
		int pageNum = wordsByPage.size();
		if (pageNum <= 150) {
		    /*
		     * Judges whether the file is in HTML code or other unknown
		     * codes
		     */
		    boolean unknownCodedDoc = unknownByPDFExtractor(wordsByPage);
		    if (unknownCodedDoc) {
			unknownCodedPDF++;
			m_docInfo
				.setErrorMsg("Sorry, this PDF document is coded with the special coders, which PDFBOX can not process successfully.");
			// System.out.println(unknownCodedPDF +
			// " PDF files are in an unknown code, which can not be processed by PDFBOX");
		    }
		    boolean isHTMLCode = true;
		    isHTMLCode = judgeHTMLCode(wordsByPage);
		    if (isHTMLCode) {
			HTMLCodePDF++;
			m_docInfo
				.setErrorMsg("Sorry, this PDF document is coded in HTML code. TableSeer does not process such files now.");
			// convertHTMLCode(wordsByPage);
			// System.out.println(HTMLCodePDF +
			// " PDF files are in HTML code, which can not be processed by PDFBOX");
		    }

		    /*
		     * currently, we only process those PDF documents that the
		     * PDF text extraction tools can process
		     */
		    // if (unknownCodedDoc==false && isHTMLCode==false) { //too
		    // much PDF files will be filtered out using this condition
		    if (isHTMLCode == false) {

			m_docInfo = computeParametersForDoc(wordsByPage);

			/*
			 * step 2: combines words into Lines, and calculates the
			 * averageLineWidth of docInfo
			 */
			ArrayList<ArrayList<TextPiece>> linesByPage = new ArrayList<ArrayList<TextPiece>>();
			float aveLineWidth = 0.0f;
			int ii = 0;
			for (ArrayList<TextPiece> wordsOfAPage : wordsByPage) {
			    ArrayList<TextPiece> linesOfAPage = combineLines(wordsOfAPage);

			    linesOfAPage = dataCleaning(linesOfAPage); // there
								       // are
								       // some
								       // noisy
								       // empty
								       // lines,
								       // we
								       // should
								       // clean
								       // them
								       // out

			    linesByPage.add(linesOfAPage);

			    for (int i = 0; i < linesOfAPage.size(); i++) {
				if (Math.max(linesOfAPage.get(i).getFontSize(),
					linesOfAPage.get(i).getXScale()) == m_docInfo
					.getBodyTextScale()) {
				    aveLineWidth = aveLineWidth
					    + linesOfAPage.get(i).getWidth();
				    ii++;
				}
			    }
			}
			aveLineWidth = aveLineWidth / (float) ii;
			if (aveLineWidth < 50.0f)
			    aveLineWidth = 175.0f; // TODO: manually fix the
						   // parameters here, we should
						   // fix it permanently
			m_docInfo.setAverageLineWidth(aveLineWidth);

			for (ArrayList<TextPiece> linesOfAPage : linesByPage) {
			    for (int i = 1; i < linesOfAPage.size() - 1; i++) {
				if ((linesOfAPage.get(i).getWidth() >= m_docInfo
					.getAverageLineWidth())
					&& (Math.abs(linesOfAPage.get(i).getY()
						- linesOfAPage.get(i - 1)
							.getY()) > 3.0)
					&& (Math.abs(linesOfAPage.get(i + 1)
						.getY()
						- linesOfAPage.get(i).getY()) > 3.0))
				    linesOfAPage.get(i).setSparseLine(false);
			    }
			}

			String meta = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\n";
			meta = meta + "<Tables>\n";
			meta = meta + "<FileName>" + pdfFile.getName()
				+ "</FileName>\n";
			meta = meta + "<pageNum>" + pageNum + "</pageNum>\n";

			xml_root.addContent(new Element("FileName")
				.addContent(pdfFile.getName()));
			xml_root.addContent(new Element("pageNum")
				.addContent(Integer.toString(pageNum)));
			m_docInfo.setDocMeta(xml_doc);
			m_docInfo.setDocMeta(meta);
			m_docInfo.setTableMetadata(meta);
			if (Config.DEBUG_MODE)
			    Debug.printMiddleResults(wordsByPage, linesByPage,
				    outputDirPath, pdfFile);

			/*
			 * step 3: identifies tables, Loop over pages
			 */
			int i = 0;
			for (ArrayList<TextPiece> linesOfAPage : linesByPage) {
			    // System.out.println("Page: " + (i+1));
			    ArrayList<TextPiece> wordsOfAPage = wordsByPage
				    .get(i);
			    extractTablesFromAPage(linesOfAPage, tables,
				    wordsOfAPage, i, pdfFile, linesByPage);

			    // extractFiguresFromAPage(linesOfAPage,
			    // wordsOfAPage, i, pdfFile, linesByPage);
			    i++;
			}
			meta = m_docInfo.getTableMetaInThisDoc();
			meta = meta + "<errorMsg>" + m_docInfo.getErrorMsg()
				+ "</errorMsg>\n";
			meta = meta + "</Tables>\n";
			// System.out.println(meta);

			/*
			 * TODO [improve]: generates XML from tables here
			 */
			if (tables.size() != 0) {
			    for (int k = 0; k < tables.size(); k++) {
				Table eTable = tables.get(k);
				Element tabRec = new Element("tableRecord")
					.setAttribute("id",
						(Integer.toString(k)));
				Element table = new Element("table");
				if (eTable.getHeight() != 0
					&& eTable.getWidth() != 0) {
				    table.setAttribute("height", Integer
					    .toString((int) eTable.getHeight()));
				    table.setAttribute("width", Integer
					    .toString((int) eTable.getWidth()));
				} else {
				    table.setAttribute("height",
					    Integer.toString(300));
				    table.setAttribute("width",
					    Integer.toString(400));
				}
				table.setAttribute("border",
					Integer.toString(1));
				tabRec.addContent(new Element("pageNumInDoc")
					.addContent(Integer.toString(eTable
						.getPageNumber())));
				tabRec.addContent(new Element("caption")
					.addContent(eTable.getCaption()));

				// table column headings
				Element tHead = new Element("thead");
				Element tRc = new Element("tr");
				tHead.addContent(tRc);
				ArrayList<String> colHeading = eTable
					.getHeading();
				for (int cloop = 0; cloop < colHeading.size(); cloop++) {
				    String head = colHeading.get(cloop);
				    tRc.addContent(new Element("th")
					    .addContent(head));
				}

				// table row contents
				Element tBody = new Element("tbody");

				ArrayList<String> rows = eTable.getTableBody();
				for (int rloop = 0; rloop < rows.size(); rloop++) {
				    Element tRr = new Element("tr");
				    String[] cells = rows.get(rloop).split(";");
				    for (int inner = 0; inner < cells.length; inner++) {
					Element tD = new Element("td")
						.addContent(cells[inner]);
					tRr.addContent(tD);
				    }
				    tBody.addContent(tRr);
				}

				table.addContent(tHead);
				table.addContent(tBody);
				tabRec.addContent(table);
				tabRec.addContent(new Element("footnote")
					.addContent(eTable.getFootNote()));
				tabRec.addContent(new Element("referenceText")
					.addContent(eTable.getRefTextList()));
				xml_tables.addContent(tabRec);
			    }
			}
			xml_root.addContent(new Element("errorMsg")
				.addContent(m_docInfo.getErrorMsg()));

			/*
			 * standard XML finish generating here, ready to output
			 */
			m_docInfo.setTableMetadata(meta);
			// System.out.println(meta);
			if (Config.DEBUG_MODE) { // print table metadata ordered
						 // by documents
			    Debug.printTableMeta(outputDirPath, pdfFile, meta);
			    Debug.printStatInfo(outputDirPath, pdfFile,
				    pageNum, m_docInfo.getTableNum());
			}
		    }// end if( not unknowCode or HTML code)
		    return tables;

		}// end if (page Num<=150)
		else {
		    largeDocNum++;
		    // System.out.println("Sorry, for the scalability and speed reasons, we do not process the PDF documents that are TOO LARGE! "
		    // + largeDocNum);
		    m_docInfo
			    .setErrorMsg("Sorry, for the scalability and speed reasons, we do not process the PDF documents that are TOO LARGE!");
		    return null;
		}
	    } else {
		noTextDocNum++;
		// System.out.println("Sorry, PDFBOX can not extract any text from this PDF document! "
		// + noTextDocNum);
		m_docInfo
			.setErrorMsg("Sorry, PDFBOX can not extract any text from this PDF document!");
		return null;
	    }
	}// end else()
    }
778124
public void writeToExcel(List<? extends Object> datas, boolean hasTitle, String path,
                             boolean transverse) throws IOException {
        writeToExcel(datas, hasTitle, path, IN_MEMORY, transverse);
    }