使用apache poi解析 Excel文件:

package excellucene;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter; import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.hssf.extractor.ExcelExtractor;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory; import com.sun.media.sound.InvalidFormatException; public class ParseExcel { public static void main(String[] args) throws IOException { String path = "C:\\Users\\Desktop\\a01hos\\img";
File f = new File(path);
File[] files = f.listFiles();
System.out.println(files.length); File[] filesxls = f.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) {
if (name.endsWith(".xls") || name.endsWith(".xlsx")) {
return true;
}
return false;
}
});
System.out.println("Excel文件有: " + filesxls.length); for (File f2 : filesxls) {
String fileDirectPathName = f2.getCanonicalPath();
System.out.println(fileDirectPathName);
// System.out.println("文件名: " + f2.getName()); new ParseExcel().parseXml(fileDirectPathName);
} /*
* IndexWriter writer; // 创建 Lucene Index Writer Directory dir =
* FSDirectory.open(Paths.get("f:/excelindex")); writer = new
* IndexWriter(dir, new IndexWriterConfig( new StandardAnalyzer()));
*
* for (File f2 : filesxls) { // FileReader fr = new FileReader(f); //
* BufferedReader br = new BufferedReader(fr);
* System.out.println(f2.getCanonicalPath()); System.out.println("文件名: "
* + f2.getName());
*
*
* // 创建dom对象创建索引 创建索引 Document document = new Document();
*
* Document doc = new Document(); doc.add(new Field("contents",
* ExcelFileReader(f2.getCanonicalPath()), TextField.TYPE_NOT_STORED));
* doc.add(new Field("filename", f2.getName(), TextField.TYPE_STORED));
* doc.add(new StringField("fullpath", f2.getCanonicalPath(),
* Field.Store.YES));
*
* writer.addDocument(doc);
*
* writer.numDocs();
*
* }
*/
} /**
* Excel表格提取数据
*
* @param fileName
* 路径
* @return
* @throws IOException
*/
public static String ExcelFileReader(String fileName) throws IOException {
InputStream path = new FileInputStream(fileName);
String content = null;
// 1、创建新的Excel文件
HSSFWorkbook wb = new HSSFWorkbook(path);
ExcelExtractor extractor = new ExcelExtractor(wb);
extractor.setFormulasNotResults(true);
extractor.setIncludeSheetNames(false);
content = extractor.getText();
return content;
} public void parseXml(String filename) {
Workbook wb = null;
try {
wb = WorkbookFactory.create(new File(filename)); Sheet sheet = wb.getSheetAt(0); for (Row row : sheet) { for (Cell cell : row) {
System.out.print(getCellValue(cell) + "---");
save(getCellValue(cell) + "---");
}
System.out.println();
}
} catch (EncryptedDocumentException e) {
e.printStackTrace();
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (org.apache.poi.openxml4j.exceptions.InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} public Object getCellValue(Cell cell) {
int type = cell.getCellType();
String show = null;
switch (type) {
case Cell.CELL_TYPE_BLANK:// 空值
show = null;
break;
case Cell.CELL_TYPE_BOOLEAN:// Boolean
show = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_ERROR:// 故障
show = String.valueOf(cell.getErrorCellValue());
break;
case Cell.CELL_TYPE_FORMULA:// 公式
show = cell.getCellFormula();
break;
case Cell.CELL_TYPE_NUMERIC:// 数字
show = String.valueOf(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:// 字符串
show = cell.getStringCellValue();
break;
default:
show = null;
}
return show;
} /**
* 保存字符串到文本中
*
* @param str
*/
public boolean save(String str) {
boolean flag = false; // 声明操作标记 String fileName = "file/haha.txt"; // 定义文件名 File f = new File(fileName); if(!f.exists()){
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
} FileWriter fw = null; // 用来写入字符文件的便捷类
PrintWriter out = null; // 向文本输出流打印对象的格式化表示形式类 try {
fw = new FileWriter(f, true); // 创建一个FileWriter
out = new PrintWriter(fw); // 创建一个PrintWriter,以追加方式将内容插入到最后一行
out.println(str); // 将字符串打印到文本中
out.flush(); // 刷新缓存 flag = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 关闭PrintWriter
if (out != null) {
out.close();
out = null;
}
// 关闭FileWriter
if (fw != null) {
fw.close();
fw = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return flag;
} }

使用lucene建立索引:

package excellucene;

import java.io.IOException;
import java.nio.file.Paths; import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory; public class SearchExcel { public static void main(String[] args) throws IOException, ParseException {
if(args.length!=2){
throw new IllegalArgumentException(SearchExcel.class.getName()+" <> <query>"); } // String indexDir = args[0];//解析输入的索引路径
// String q = args[1];//解析输入的查询字符串 String indexDir = "F:\\excelindex";
String q = "zhangxing"; search(indexDir, q); } public static void search(String indexDir, String q) throws IOException, ParseException{
// Directory dir = FSDirectory.open(Paths.get(indexDir)); IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(indexDir))); IndexSearcher is = new IndexSearcher(reader); Analyzer analyzer = new StandardAnalyzer(); // 需要添加 .jar 包
// lucene-queryparser-7.4.0.jar QueryParser parser = new QueryParser("filename", analyzer); Query query = parser.parse(q); long start = System.currentTimeMillis();
TopDocs hits = is.search(query, 10);
long end = System.currentTimeMillis(); System.err.println("Found "+hits.totalHits+" document(s) (in "+ (end-start) +" milliseconds) that matched query'"+q+"':"); for(ScoreDoc scoreDoc:hits.scoreDocs){
Document doc = is.doc(scoreDoc.doc);
System.out.println(doc.get("fullpath")); }
}
}

使用了的jar包:

Apache POI使用的更多相关文章

  1. 简单使用Apache POI

    Apache POI是一个纯Java编写用来操作Microsoft Office的框架,最常见的应用是让服务器后台按照特定的数据生成Excel表格提供给用户实用.前段时间因为项目的需要被大量使用,使用 ...

  2. 使用maven引入Apache poi jar包

    maven构建的项目-->pom.xml文件 eclipse提供Dependencies直接添加依赖jar包的工具:直接搜索poi以及poi-ooxml即可,maven会自动依赖需要的jar包: ...

  3. apache poi导出excel报表

    Apache POI 是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程式对Microsoft Office格式档案读和写的功能.POI为"P ...

  4. Apache POI 实现对 Excel 文件读写

    1. Apache POI 简介 Apache POI是Apache软件基金会的开放源码函式库. 提供API给Java应用程序对Microsoft Office格式档案读和写的功能. 老外起名字总是很 ...

  5. APACHE POI教程 --java应用程序用POI与Excel交互

    POI报表 --用POI与Excel交互 AURISOFT 第一章 POI简介 --Jakata Poi HSSF:纯java的Excel解决方案 在我们实际的开发中,表现层的解决方案虽然有多样,但是 ...

  6. apache poi 生成excel

    ExcelBuilder.Java package com.coracle.yk.xmanager.util.poi; import com.coracle.yk.xframework.util.Bl ...

  7. weblogic 12c下jxls导出excel报错Could not initialize class org.apache.poi.xssf.usermodel.XSSFVMLDrawing

    周一,开发反馈weblogic 12c下jxls导出excel报错,公司环境和UAT环境均报错,看日志如下: 2016-06-08 09:16:55,825 ERROR org.jxls.util.T ...

  8. [转]How to insert a row between two rows in an existing excel with HSSF (Apache POI)

    本文转自:http://stackoverflow.com/questions/5785724/how-to-insert-a-row-between-two-rows-in-an-existing- ...

  9. 如何用Apache POI操作Excel文件-----如何对一个单元格加注解?

    有的时候,我们需要通过操作Apache POI,在生成Cell数据的同时,能对其生成的Cell,加上注解(comments),类似于下面的. 那么对于这种情况,我们的代码应该如何写呢? 借花献佛,我就 ...

  10. 如何用Apache POI操作Excel文件-----如何在已有的Excel文件中插入一行新的数据?

    在POI的第一节入门中,我们提供了两个简单的例子,一个是如何用Apache POI新建一个工作薄,另外一个例子是,如果用Apache POI新建一个工作表.那么在这个章节里面,我将会给大家演示一下,如 ...

随机推荐

  1. Mysql+innodb数据存储逻辑

    Mysql+innodb数据存储逻辑. 表空间由段,区,页组成 ibdata1:共享表空间.即所有的数据都存放在这个表空间内.如果用户启用了innodb_file_per_table,则每张表内的数据 ...

  2. DP Intro - poj 2342 Anniversary party

    今天开始做老师给的专辑,打开DP专辑 A题 Rebuilding Roads 直接不会了,发现是树形DP,百度了下了该题,看了老半天看不懂,想死的冲动都有了~~~~ 最后百度了下,树形DP入门,找到了 ...

  3. 宜人贷项目里-----正则匹配input输入月份规则

    在标签上可以直接进行校验如下,如果只调数字键盘type=number不好用可以用type=tel <input name="creditDate" oninput=" ...

  4. linux下定时任务的工具crontab的用法

    Linux计划任务工具cron用法详解 linux下大名鼎鼎的计划任务工具crontab的使用介绍baidu.google上多得让人眼花缭乱,本着“天下文章一大抄”的觉悟,加上本人日常工作中总结的使用 ...

  5. C# CultureInfo中常用的InvariantCulture

    本文参考自CultureInfo中重要的InvariantCulture,纯属读书笔记,加深记忆 1.CultureInfo的InvariantCulture的作用 (1).CultureInfo使整 ...

  6. Robot Framework(Databaselibrary库操作)

    1.安装 DatabaseLibrary 库 DatabaseLibrary 下载地址:https://pypi.python.org/pypi/robotframework-databaselibr ...

  7. Spark standalone简介与运行wordcount(master、slave1和slave2)

    前期博客 Spark standalone模式的安装(spark-1.6.1-bin-hadoop2.6.tgz)(master.slave1和slave2)  Spark运行模式概述 1. Stan ...

  8. JSP页面GET传值乱码问题

    两个JSP页面进行GET传值的时候.两个页面的编码都是UTF-8,且传值之前设置response的content为UTF-8也解决不了问题. 设置tomcat的配置文件server.xml:在Conn ...

  9. CCF 出现次数最多的数 201312-1

    出现次数最多的数 问题描述 试题编号: 201312-1 试题名称: 出现次数最多的数 时间限制: 1.0s 内存限制: 256.0MB 问题描述: 问题描述 给定n个正整数,找出它们中出现次数最多的 ...

  10. 面试题目: 获取服务器IP和客户端IP

    [面试题目] 怎么获取服务器IP和客户端IP地址? I. PHP获取客户端IP, 可通过下面系统变量 1. $_SERVER['Remote_Addr'] 2. $_SERVER['HTTP_CLIE ...