天天看點

java 分頁導出word_Java導出Word問題

//使用的是Apache POI

public static String readWord(InputStream ins)throws Exception

{

StringBuffer sRet=new StringBuffer();

byte[] bContent = null;

ByteArrayOutputStream outs = null;

byte[] head = new byte[8];

byte[] bHead = new byte[] {-48, -49, 17, -32, -95, -79, 26, -31};

boolean bFlag = false;

ByteArrayInputStream bis=null;

try {

if(ins==null)

{

throw new Exception("檔案流不存在!");

}

outs = new ByteArrayOutputStream();

bContent = new byte[2048];

int j = -1;

while ((j = ins.read(bContent)) != -1)

{

outs.write(bContent, 0, j);

}

outs.flush();

bContent = outs.toByteArray();

outs.close();

for (int i = 0; i < head.length; i++)

{

if (bContent[i] != bHead[i])

{

bFlag = true;

break;

}

}

bis=new ByteArrayInputStream(bContent);

if (bFlag)//word 2007

{

XWPFParagraph xph=null;

XWPFDocument document = new XWPFDocument(bis);

Iterator it = document.getParagraphsIterator();

while (it.hasNext())

{

xph = it.next();

sRet.append(xph.getParagraphText()+"\n");

}

}

else//word2003

{

HWPFDocument document = new HWPFDocument(bis);

Range bodyRange = document.getRange();

Paragraph ph=null;

// 段落

for (int h = 0; h < bodyRange.numParagraphs(); h++)

{

ph = bodyRange.getParagraph(h);

sRet.append(ph.text());

}

}

} catch (Exception e) {

throw e;

}finally

{

outs.close();

}

return sRet.toString();

}