您的位置:首页 > Web前端 > HTML

读取Doc,Excel,PDF,html,生成Txt文件,读取Txt生成Excel文件

2011-08-01 15:35 826 查看
packageoffice;

/**
*读取Doc,Excel,PDF,html,生成Txt文件,读取Txt生成Excel文件
*@authorJavaAlpha
*@date2011-8-1
*@versionV1.0
*/

importjava.io.BufferedReader;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.FileOutputStream;
importjava.io.FileReader;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.InputStreamReader;
importjava.io.OutputStreamWriter;
importjava.io.Writer;
importjava.net.MalformedURLException;
importjava.net.URL;
importjava.util.HashMap;
importjava.util.Iterator;
importjava.util.Map;
importjavax.swing.text.BadLocationException;
importjavax.swing.text.DefaultStyledDocument;
importjavax.swing.text.rtf.RTFEditorKit;
importorg.apache.poi.hssf.usermodel.HSSFCell;
importorg.apache.poi.hssf.usermodel.HSSFRow;
importorg.apache.poi.hssf.usermodel.HSSFSheet;
importorg.apache.poi.hssf.usermodel.HSSFWorkbook;
importorg.pdfbox.pdfparser.PDFParser;
importorg.pdfbox.pdmodel.PDDocument;
importorg.pdfbox.util.PDFTextStripper;
importorg.textmining.text.extraction.WordExtractor;
publicclassReadOffice{

/**
*@paramargs
*/
publicstaticvoidmain(String[]args){
//readDoc("e:/1.doc");
//readExcel("e:/1.xls");
//readPDF("e:/1.pdf");
//readHtml("e:/1.html");
readHtmlAll("e:/1.html");
}

/**
*创建TXT文件,写入文件内容
*
*@paramtext
*/

staticvoidcreateTXTAndWriteDoc(Stringtext,Stringpath){
FileOutputStreamfos=null;
FileOutputStreamout=null;
try{
//新建一输出文件流,如果文件存在先删除文件
Filef=newFile(path);
if(f.exists()){
f.delete();
}

fos=newFileOutputStream(f);
out=newFileOutputStream(f);
byte[]b=text.getBytes("GB2312");
out.write(b);
out.flush();

System.out.println("文件生成...");
}catch(Exceptione){
System.out.println("出现异常:"+e);
}finally{
try{
if(null!=fos){
fos.close();
}
}catch(IOExceptione){
e.printStackTrace();
}
try{
if(null!=out){
out.close();
}
}catch(IOExceptione){
e.printStackTrace();
}
fos=null;
out=null;
}
}

/**
*读取DOC文件
*
*@paramdir
*@throwsException
*/
staticvoidreadDoc(Stringdir){
//创建输入流读取doc文件
FileInputStreamin=null;
WordExtractorextractor=null;
Stringtext=null;
try{
in=newFileInputStream(newFile(dir));
//创建WordExtractor
extractor=newWordExtractor();
//对doc文件进行提取
text=extractor.extractText(in);
System.out.println("text1:"+text);
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(Exceptione){
e.printStackTrace();
}finally{
try{
if(null!=in){
in.close();
}
}catch(IOExceptione){
e.printStackTrace();
}
in=null;
}
//写入文件内容
createTXTAndWriteDoc(text,"e:/doc.txt");
}

/**
*读取Excel文件
*
*@paramdir
*/
@SuppressWarnings("deprecation")
staticvoidreadExcel(Stringdir){
/**
*@paramfilePath
*文件路径
*@return读出的Excel的内容
*/
StringBufferbuff=newStringBuffer();
try{
//创建对Excel工作簿文件的引用
HSSFWorkbookwb=newHSSFWorkbook(newFileInputStream(dir));
//创建对工作表的引用。
for(intnumSheets=0;numSheets<wb.getNumberOfSheets();numSheets++){
if(null!=wb.getSheetAt(numSheets)){
HSSFSheetaSheet=wb.getSheetAt(numSheets);//获得一个sheet
for(introwNumOfSheet=0;rowNumOfSheet<=aSheet.getLastRowNum();rowNumOfSheet++){
if(null!=aSheet.getRow(rowNumOfSheet)){
HSSFRowaRow=aSheet.getRow(rowNumOfSheet);//获得一个行
for(intcellNumOfRow=0;cellNumOfRow<=aRow.getLastCellNum();cellNumOfRow++){
if(null!=aRow.getCell((short)cellNumOfRow)){
HSSFCellaCell=aRow.getCell((short)cellNumOfRow);//获得列值
switch(aCell.getCellType()){
caseHSSFCell.CELL_TYPE_FORMULA:
break;
caseHSSFCell.CELL_TYPE_NUMERIC:
buff.append(aCell.getNumericCellValue()).append('');
break;
caseHSSFCell.CELL_TYPE_STRING:
buff.append(aCell.getStringCellValue()).append('');
break;
}
}
}
buff.append('');
}
}
}
}
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
//写入文件内容
createTXTAndWriteDoc(buff.toString(),"e:/excel.txt");
}

/**
*读取Powerpoint文件
*
*@paramdir
*/
staticvoidreadPPT(Stringdir){

}

/**
*读取PDF文件
*
*@paramdir
*/
staticvoidreadPDF(Stringdir){
Stringresult=null;
FileInputStreamis=null;
PDDocumentdocument=null;
try{
is=newFileInputStream(dir);
PDFParserparser=newPDFParser(is);
parser.parse();
document=parser.getPDDocument();
PDFTextStripperstripper=newPDFTextStripper();
result=stripper.getText(document);
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}finally{
if(null!=is){
try{
is.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
if(null!=document){
try{
document.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
//写入文件内容
createTXTAndWriteDoc(result,"e:/pdf.txt");
}

/**
*//读取pdf文件
*
*@paramfile
*@throwsException
*/
publicvoidreadPdf(Stringfile)throwsException{
//是否排序
booleansort=false;
//pdf文件名
StringpdfFile=file;
//输入文本文件名称
StringtextFile=null;
//编码方式
Stringencoding="GB2312";
//开始提取页数
intstartPage=1;
//结束提取页数
intendPage=Integer.MAX_VALUE;
//文件输入流,生成文本文件
Writeroutput=null;
//内存中存储的PDFDocument
PDDocumentdocument=null;
try{
try{
//首先当作一个URL来装载文件,如果得到异常再从本地文件系统//去装载文件
URLurl=newURL(pdfFile);//注意参数已不是以前版本中的URL.而是File。
document=PDDocument.load(pdfFile);
//获取PDF的文件名
StringfileName=url.getFile();
//以原来PDF的名称来命名新产生的txt文件
if(fileName.length()>4){
FileoutputFile=newFile(fileName.substring(0,fileName.length()-4)+".txt");
textFile=outputFile.getName();
}
}catch(MalformedURLExceptione){
//如果作为URL装载得到异常则从文件系统装载//注意参数已不是以前版本中的URL.而是File。
document=PDDocument.load(pdfFile);
if(pdfFile.length()>4){
textFile=pdfFile.substring(0,pdfFile.length()-4)+".txt";
}
}
//文件输入流,写入文件倒textFile
output=newOutputStreamWriter(newFileOutputStream(textFile),encoding);
//PDFTextStripper来提取文本
PDFTextStripperstripper=null;
stripper=newPDFTextStripper();
//设置是否排序
stripper.setSortByPosition(sort);
//设置起始页
stripper.setStartPage(startPage);
//设置结束页
System.out.print(stripper.getText(document));
stripper.setEndPage(endPage);
//调用PDFTextStripper的writeText提取并输出文本
stripper.writeText(document,output);
}finally{
if(output!=null){
//关闭输出流
output.close();
}
if(document!=null){
//关闭PDFDocument
document.close();
}
}
}

/**
*读取Txt文件
*
*@paramfilePath
*@return
*@throwsException
*/
publicStringgetTextFromTxt(StringfilePath)throwsException{
FileReaderfr=newFileReader(filePath);
BufferedReaderbr=newBufferedReader(fr);
StringBufferbuff=newStringBuffer();
Stringtemp=null;
while((temp=br.readLine())!=null){
buff.append(temp+"");
}
br.close();
returnbuff.toString();
}

/**
*读取RTF文件内容
*
*@paramfilePath
*@return
*/
publicStringgetTextFromRtf(StringfilePath){
Stringresult=null;
Filefile=newFile(filePath);
try{
DefaultStyledDocumentstyledDoc=newDefaultStyledDocument();
InputStreamis=newFileInputStream(file);
newRTFEditorKit().read(is,styledDoc,0);
result=newString(styledDoc.getText(0,styledDoc.getLength()).getBytes("ISO8859_1"));
//提取文本,读取中文需要使用ISO8859_1编码,否则会出现乱码
}catch(IOExceptione){
e.printStackTrace();
}catch(BadLocationExceptione){
e.printStackTrace();
}
returnresult;
}

/**
*@paramfilePath
*文件路径
*@return获得html的全部内容
*/

publicstaticStringreadHtml(StringfilePath){
BufferedReaderbr=null;
StringBuffersb=newStringBuffer();
try{
br=newBufferedReader(newInputStreamReader(newFileInputStream(filePath),"GB2312"));
Stringtemp=null;
while((temp=br.readLine())!=null){
sb.append(temp);
}
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
//写入文件内容
createTXTAndWriteDoc(sb.toString(),"e:/html.txt");
returnsb.toString();
}

/**
*@paramfilePath
*文件路径
*@return获得的html文本内容
*/
publicstaticvoidreadHtmlAll(StringfilePath){
//得到body标签中的内容
Stringstr=readHtml(filePath);
StringBufferbuff=newStringBuffer();
intmaxindex=str.length()-1;
intbegin=0;
intend;
//截取>和<之间的内容
while((begin=str.indexOf('>',begin))<maxindex){
end=str.indexOf('<',begin);
if(end-begin>1){
buff.append(str.substring(++begin,end));
}
begin=end+1;
}
//写入文件内容
createTXTAndWriteDoc(buff.toString(),"e:/htmlAll.txt");
//returnbuff.toString();
}

/**
*以行为单位读取文件(文本文件)
*
*@paramfilePath
*/
publicstaticvoidreadFileByLine(StringfilePath){
Filefile=newFile(filePath);
BufferedReaderbd=null;
Map<String,String>str=newHashMap<String,String>();
Strings1="";
Strings2="";

try{
bd=newBufferedReader(newInputStreamReader(newFileInputStream(file),"gb2312"));//编码转换(关键的地方)

Stringtemp="";
intline=1;
while((temp=bd.readLine())!=null){
if(temp.length()>0){
s1=temp.substring(0,3);
s1=s1.trim();
s2=temp.substring(4);
s2=s2.trim();
str.put(s1,s2);
}
++line;
}
createExcel(str);

}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}finally{
try{
if(bd!=null)
bd.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}

/**
*输出Excel文件,输出格式为多行两列
*
*@parammap
*/
@SuppressWarnings({"deprecation","unchecked"})
staticvoidcreateExcel(Map<String,String>map){
try{
//新建一输出文件流
FileOutputStreamfOut=newFileOutputStream("e:/2.xls");
Filefile=newFile("e:/2.xls");
if(file.exists()){
file.delete();
}
//创建新的Excel工作簿
HSSFWorkbookworkbook=newHSSFWorkbook();
//在Excel工作簿中建一工作表,其名为缺省值
//如要新建一名为"联系人用户名和电话"的工作表,其语句为:
HSSFSheetsheet=workbook.createSheet("联系人用户名和电话");
HSSFRowrow=null;
//在索引0的位置创建单元格(左上端)
HSSFCellcell1=null;
HSSFCellcell2=null;

Iteratoriter=map.entrySet().iterator();
inti=0;

while(iter.hasNext()){
Map.Entryentry=(Map.Entry)iter.next();
Objectkey=entry.getKey();
Objectval=entry.getValue();
row=sheet.createRow((short)i++);
cell1=row.createCell((short)0);
cell2=row.createCell((short)1);
//定义单元格为字符串类型
cell1.setCellType(HSSFCell.CELL_TYPE_STRING);
cell2.setCellType(HSSFCell.CELL_TYPE_STRING);

//在单元格中输入一些内容
cell1.setCellValue(key.toString());
cell2.setCellValue(val.toString());

if(i>255){
break;
}
}

//把相应的Excel工作簿存盘
workbook.write(fOut);
fOut.flush();
//操作结束,关闭文件
fOut.close();
System.out.println("文件生成...");

}catch(Exceptione){
System.out.println("出现异常:"+e);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: