java读取word文档
在java中在JTextarea中显示word的内容,用到poi
但是在textarea中显示的时候乱码了,textarea中是不是好像不能显示图片,但是也不能显示文字吗,好像可以用Jtextpane显示,
但是现在做了一大半,求高人指导下思路
[最优解释]
乱码都是由于出入编码不一致导致的,你可以在各个关键步骤打印出编码格式,就知道是哪里的问题了
[其他解释]
看了一楼用的两个类,我不信你这样能读Word文档。Javadoc中写到,FileReader is meant for reading streams of characters. Word文档不是文本格式,所以你直接用FileReader根本不行。BufferedReader这个类也是读文本的,比如说你关键的那句str=br.readLine(),Javadoc里面这么写的:
public String readLine()
Read a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
Word文档遵守这样的格式?? 不可能。
[其他解释]
我以前关注这个问题,在网上搜了下,说word的代码不开源所以读不到,但是excel中的内容倒是可以读取
[其他解释]
你是编码的问题,JtextPane可以显示图片,比如qq中的显示表情,java中可以用jtextPane实现
[其他解释]
图片显示要用JLabel。
JTextarea是可以显示文字的。
word和txt没什么区别,都是用输入输出流读取。
String s="";
fr=new FileReader("src/com/briup/ch11/wtmpx");
br=new BufferedReader(fr);
String str="";
while((str=br.readLine())!=null){
s+=str;}
br.close();
br=new BufferedReader
(new InputStreamReader
(new FileInputStream(file),"GBK"));//file指的是你文件路径,GBK你的文件的格式
public void read() throws IOException{
File f = new File(ReaderListener.path);
InputStream in =new FileInputStream(f);
HWPFDocument msWord=new HWPFDocument(in);
Range range = msWord.getRange();
PicturesTable pTable = msWord.getPicturesTable();//获取图表对象
int numCharacterRuns = msWord.getRange().numCharacterRuns();//获取文档的段落
@SuppressWarnings("rawtypes")
//ArrayList content = new ArrayList();
byte[] content = null;
for (int i = 0; i < numCharacterRuns; i++) {
//CharacterRun这个类表示一个文本运行,有着共同的属性。
CharacterRun characterRun = msWord.getRange().getCharacterRun(i);
//判断,是图片则把图片位置替换为image标签,再把图片输出到指定位置
if (pTable.hasPicture(characterRun)) {
Picture pic = pTable.extractPicture(characterRun, true);//选取ptable中picture
//试建议的文件名:在“数据”流和扩展,试图确定图片的内容从第一个字节的十六进制表示的图像结构失调。
content = pic.getContent();//获取图片内容的字节数组
ReaderGUI.text.insertIcon(new ImageIcon(content));
} else {//纯文本则直接拼接
ReaderGUI.text.replaceSelection(characterRun.text()+"\n");
}//System.out.println(text);
}
//ReaderGUI.text.replaceSelection(range.text());
System.out.println(content.length);
in.close();
}