Java 写rtf(word) excel文件

来源:互联网 发布:推荐淘宝内部券qq群 编辑:程序博客网 时间:2024/05/18 15:06

 

二、下面就简单的解释一下这几个文件

 

1. ExcelGenerate .java文件 这个文件中每个方法都有解释,好好的看看注释

 

import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.util.CellRangeAddress;

/**
 *
 * @author 岑
 *
 */
public class ExcelGenerate {

 public static HSSFWorkbook wb;
 
 private static HSSFSheet sheet;
 
 private static HSSFRow newRow;
 
 private static HSSFCellStyle cellSytle;
 
 private static HSSFCell newCell;
 
 ExcelGenerate() {
  wb = new HSSFWorkbook();
 }
 
 public HSSFWorkbook getInstance() {
  if (wb == null) {
   wb = new HSSFWorkbook();
  }
  return wb;
 }
 
 /**
  *  sheet 取得
  * @param sheet 对象 HSSFSheet
  */
 public static HSSFSheet getSheet(String sheetName) {
  sheet = wb.createSheet(sheetName);
  return sheet;
 }
 
 /**
  * 新建行
  *
  * @param sheet HSSFSheet 对象
  * @param rownum 行号 0:第一行 1:第2行...
  * @return row HSSFRow 对象
  */
 public static HSSFRow getNewRow(HSSFSheet sheet, int rownum) {
  newRow = sheet.createRow(rownum);
  return newRow;
 }
 
 public static HSSFCell getNewCell(HSSFRow row, int cellnum) {
  newCell = row.createCell(cellnum);
  return newCell;
 }
 /**
  * 合并单元格
  *
  * @param firstRow 开始行
  * @param lastRow  结束行
  * @param firstCol 开始列
  * @param lastCol  结束列
  */
 public static void CellMergedRegion(int firstRow, int lastRow, int firstCol, int lastCol) {
  CellRangeAddress region = new CellRangeAddress(firstRow, lastRow, firstCol,lastCol);
  sheet.addMergedRegion(region);
 }
 
 /**
  * 样式表
  *
  * @return CellStyle HSSFCellStyle
  */
 public static HSSFCellStyle getCellStyle() {
  // 创建单元格样式
  cellSytle = wb.createCellStyle();
  return cellSytle;
 }
 
 /**
  * 设置单元格边框
  *
  * @param colour 边框颜色 例如: HSSFColor.RED.index
  * @param borderBottom 边框底部 例如:HSSFCellStyle.BORDER_THIN
  * @param borderLeft 边框左边 例如:HSSFCellStyle.BORDER_THIN
  * @param borderRight 边框右边 例如:HSSFCellStyle.BORDER_THIN
  * @param borderTop 边框顶部 例如:HSSFCellStyle.BORDER_THIN
  * @see org.apache.poi.hssf.util.HSSFColor;
  * @see org.apache.poi.hssf.usermodel.HSSFCellStyle
  *
  */
 public static void setBorder(HSSFCellStyle sytle,short colour, short borderBottom, short borderLeft, short borderRight, short borderTop) {
  // 设置单元格边框
  sytle.setBottomBorderColor(colour);
  sytle.setBorderBottom(borderBottom);
  sytle.setBorderLeft(borderLeft);
  sytle.setBorderRight(borderRight);
  sytle.setBorderTop(borderTop);
 }
 
 /**
  * 设置单元格颜色
  *
  * @param colour 颜色设定 例如: HSSFColor.RED.index
  * @param fillPattern 填充颜色 例如:HHSSFCellStyle.SOLID_FOREGROUND
  * @see org.apache.poi.hssf.util.HSSFColor;
  * @see org.apache.poi.hssf.usermodel.HSSFCellStyle
  */
 public static void setForegroundColor(HSSFCellStyle sytle,int colour, int fillPattern) {
  // 设定单元格背景色
  sytle.setFillForegroundColor(HSSFColor.WHITE.index);
  sytle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
 }
 
 /**
  * 画表格
  *
  * @param startRow 开始行
  * @param endRow 结束行
  * @param startCell 开始格
  * @param endCell 结束格
  * @param cellSytle 表格样式
  */
 public static void setChart(int startRow, int endRow, int startCell, int endCell, HSSFCellStyle cellSytle){
  for (int i = startRow; i <= endRow; i++) {
   newRow = sheet.createRow(i);
   for (int j = startCell; j <= endCell; j++) {
    newCell = newRow.createCell(j);
    newCell.setCellStyle(cellSytle);
   }
  }
 }
 
 /**
  *
  * @param wb 工作表
  * @param filePath 文件名和路径
  * @throws IOException
  * @throws Exception
  */
 public static void saveFile(HSSFWorkbook wb, String filePath) throws IOException, Exception {
  FileOutputStream newFile = new FileOutputStream(filePath);
  wb.write(newFile);
  newFile.close();
 }
 
 /**
  * 列宽设定
  *
  * @param colNun 列号 0: 第一列....
  * @param weight 列宽 1000、2000、3000 ...
  */
 public static void setColSytle(int colNun ,int weight) {
   sheet.setColumnWidth(colNun, weight);
 }
}

 

2. ExcelGenerateForTest .java测试文件

 

package cn.com.report.document.excel;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;

/**
 * @author 岑
 *
 */
public class ExcelGenerateForTest {

 /**
  * @param args
  */
 public static void main(String[] args) {
  try {
   
   // 创建Excel的工作表,对应到一个excel文档
   HSSFWorkbook wb = new ExcelGenerate().getInstance();

   // Sheet做成
   HSSFSheet sheet = ExcelGenerate.getSheet("sheet1");
   HSSFRow row = ExcelGenerate.getNewRow(sheet, 0);
   HSSFCell cell = ExcelGenerate.getNewCell(row, 0);
   // 设置excel每列宽度
   ExcelGenerate.setColSytle(0, 1000);
   
   /**
    * 报表标题
    */
   // 单元个合并
   ExcelGenerate.CellMergedRegion(0, 3, 0, 12);

   // 创建字体样式
   HSSFFont font = wb.createFont();
   font.setFontName("宋体");
   font.setBoldweight((short) 200);
   font.setFontHeight((short) 200);
   font.setColor(HSSFColor.BLUE.index2);

   // 创建单元格样式
   
   HSSFCellStyle cellSytle = ExcelGenerate.getCellStyle();
   
   cellSytle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
   cellSytle.setAlignment(CellStyle.ALIGN_CENTER);
   cellSytle.setFont(font);
   
   // 设定单元格背景色
   ExcelGenerate.setForegroundColor(cellSytle,HSSFColor.WHITE.index, HSSFCellStyle.SOLID_FOREGROUND);   
   // 设置单元格边框
   ExcelGenerate.setBorder(cellSytle,HSSFColor.BLACK.index, HSSFCellStyle.BORDER_THIN,
     HSSFCellStyle.BORDER_THIN, HSSFCellStyle.BORDER_THIN, HSSFCellStyle.BORDER_THIN);

   // 填充单元格
   ExcelGenerate.setChart(0, 3, 0, 12, cellSytle);
   
   cell.setCellStyle(cellSytle);
   cell.setCellValue("指标");
   // 这里是生成的文档和路径,根据自己的实际情况修改
   String path = "c://document//workbook1.xls";
   ExcelGenerate.saveFile(wb, path);
  } catch (Exception e) {
   System.out.println("已运行 xlCreate() : " + e);
  }

 }

}

3、这个文件是我没用我封装过的包写的,直接拷贝source,改一下文件路径就可以运行了

package cn.com.report.document.excel;

import java.io.FileOutputStream;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.util.CellRangeAddress;

public class ExcelGenerateTest {

 /**
  * @param args
  */
 public static void main(String[] args) {
  try {

   // 创建Excel的工作表,对应到一个excel文档
   HSSFWorkbook wb = new HSSFWorkbook();

   // Sheet做成
   HSSFSheet sheet = wb.createSheet("new sheet");

   // 设置excel每列宽度
   sheet.setColumnWidth(0, 1000);

   /**
    * 报表标题
    */
   // 单元个合并
   CellRangeAddress region = new CellRangeAddress(0, (short) 3, 0,
     (short) 12);
   HSSFRow row = sheet.createRow(0);
   HSSFCell cell = row.createCell(0);
   sheet.addMergedRegion(region);

   // 创建字体样式
   HSSFFont font = wb.createFont();
   font.setFontName("宋体");
   font.setBoldweight((short) 500);
   font.setFontHeight((short) 500);
   font.setColor(HSSFColor.BLUE.index2);

   // 创建单元格样式
   HSSFCellStyle cellSytle = wb.createCellStyle();
   cellSytle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
   cellSytle.setAlignment(CellStyle.ALIGN_CENTER);
   cellSytle.setFont(font);
   // 设定单元格背景色
   cellSytle.setFillForegroundColor(HSSFColor.WHITE.index);
   cellSytle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
   // 设置单元格边框
   cellSytle.setBottomBorderColor(HSSFColor.RED.index);
   cellSytle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
   cellSytle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
   cellSytle.setBorderRight(HSSFCellStyle.BORDER_THIN);
   cellSytle.setBorderTop(HSSFCellStyle.BORDER_THIN);

   // 填充单元格
   cell.setCellStyle(cellSytle);
   cell.setCellValue("指标");

   /**
    * 报表内容
    */
   // 创建字体样式
   HSSFFont font1 = wb.createFont();
   font1.setFontName("宋体");
//   font1.setBoldweight((short) 200);
   font1.setFontHeight((short) 250);
   font1.setColor(HSSFColor.BLUE.index2);
   
   HSSFCellStyle cellSytle1 = wb.createCellStyle();
   // 设定单元格背景色
   cellSytle1.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
   cellSytle1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
   // 设定单元格边框
   cellSytle1.setBottomBorderColor(HSSFColor.BLACK.index);
   cellSytle1.setBorderBottom(HSSFCellStyle.BORDER_THIN);
   cellSytle1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
   cellSytle1.setBorderRight(HSSFCellStyle.BORDER_THIN);
   cellSytle1.setBorderTop(HSSFCellStyle.BORDER_THIN);
   cellSytle1.setFont(font1);
   // 报表表头
   for (int i = 4; i < 5; i++) {
    row = sheet.createRow(i);
    for (int j = 0; j <= 12; j++) {
     cell = row.createCell(j);
     if (j == 1) {
      // 设置excel列宽度
      sheet.setColumnWidth(j, 4000);
      cell.setCellValue("一级指标");
     }
     if (j == 2) {
      sheet.setColumnWidth(j, 2000);
      cell.setCellValue("权重");
     }

     if (j == 3) {
      sheet.setColumnWidth(j, 4000);
      cell.setCellValue("二级指标");
     }

     if (j == 4) {
      sheet.setColumnWidth(j, 2000);
      cell.setCellValue("权重");
     }

     if (j == 5) {
      sheet.setColumnWidth(j, 5000);
      cell.setCellValue("评测标准");
     }

     if (j == 6) {
      sheet.setColumnWidth(j, 5000);
      cell.setCellValue("指标内容");
     }

     if (j == 7) {
      sheet.setColumnWidth(j, 2000);
      cell.setCellValue("权重");
     }

     if (j == 8) {
      sheet.setColumnWidth(j, 5000);
      cell.setCellValue("指标细则");
     }

     if (j == 9) {
      sheet.setColumnWidth(j, 4000);
      cell.setCellValue("权重比例");
     }

     if (j == 10) {
      sheet.setColumnWidth(j, 5000);
      cell.setCellValue("细则评分");
     }
     if (j == 11) {
      sheet.setColumnWidth(j, 4000);
      cell.setCellValue("评分(推荐)");
     }
     if (j == 12) {
      sheet.setColumnWidth(j, 6000);
      cell.setCellValue("细则评分(推荐评语");
     }
     cell.setCellStyle(cellSytle1);
    }
   }
   
   // 报表内容
   // 单元个合并
   HSSFCellStyle cellSytle5 = wb.createCellStyle();
   // 设定单元格边框
   cellSytle5.setBottomBorderColor(HSSFColor.BLACK.index);
   cellSytle5.setBorderBottom(HSSFCellStyle.BORDER_THIN);
   cellSytle5.setBorderLeft(HSSFCellStyle.BORDER_THIN);
   cellSytle5.setBorderRight(HSSFCellStyle.BORDER_THIN);
   cellSytle5.setBorderTop(HSSFCellStyle.BORDER_THIN);
   
   // 表格划线
   for (int i = 5; i <= 15; i++) {
    row = sheet.createRow(i);
    for (int j = 0; j <= 12; j++) {
     cell = row.createCell(j);
     cell.setCellStyle(cellSytle5);
    }
   }
   // 合并单元格
   CellRangeAddress region1 = new CellRangeAddress(5, (short) 15, 1,
     (short) 1);
   sheet.addMergedRegion(region1);
   row = sheet.getRow(5);
   cell = row.getCell(1);
   cell.setCellValue("1信息公开");


   // 这里是生成的文档和路径,根据自己的实际情况修改
   FileOutputStream fileOut = new FileOutputStream( "c://document//workbook1.xls");   

  wb.write(fileOut);


   fileOut.close();
  } catch (Exception e) {
   System.out.println("已运行 xlCreate() : " + e);
  }
 }
}

三、word文档的生成,其实我做的是rtf文件,生成的时候把后缀名改成了.doc了

 

1、FontContant .java字体定义路径

/**
 * @author 岑
 *
 * windows字体库定义,如果是liunx的话 /usr/share/fonts 路径下的字体
 */
public interface FontContant {
 public static final String SIMKAI = "c://windows//fonts//SIMKAI.ttf";
 public static final String FZSTK = "c://windows//fonts//FZSTK.ttf";
 public static final String FZYTK = "c://windows//fonts//FZYTK.ttf";
 public static final String SIMFANG = "c://windows//fonts//SIMFANG.TTF";
 public static final String SIMHEI = "c://windows//fonts//SIMHEI.TTF";
 public static final String STCAIYUN = "c://windows//fonts//STCAIYUN.TTF";
 public static final String STFANGSO = "c://windows//fonts//STFANGSO.TTF";
 public static final String STXIHEI = "c://windows//fonts//STXIHEI.TTF";
 public static final String STXINWEI = "c://windows//fonts//STXINWEI.TTF";
 public static final String STXINGKA = "c://windows//fonts//STXINGKA.TTF";
 public static final String STZHONGS = "c://windows//fonts//STZHONGS.TTF";
 public static final String SIMLI = "c://windows//fonts//SIMLI.TTF";
 public static final String SIMSUN = "c://windows//fonts//SIMSUN.TTC";
 public static final String SURSONG = "c://windows//fonts//SURSONG.TTF";
 public static final String SIMYOU = "c://windows//fonts//SIMYOU.TTF";
}

 2、WordGenerate.java word 或rtf文件的生成

 

package cn.com.report.document.word;

import java.io.FileOutputStream;
import java.io.IOException;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.rtf.RtfWriter2;

/**
 * rtf生成
 *
 * @author 岑
 * @version 1.0.1 2010.03.31
 */

public class WordGenerate implements FontContant{
 
 private static Document document;
 
 /**
  *
  */
 private static Rectangle  pageSize;
 
 /**
  * 系统字体
  */
 private static BaseFont bfChinese;

 /**
  * 字体
  */
 private static Font font;
 
 /**
  * 文档段落
  */
 private static Paragraph paragraph;

 /**
  * 图片对象
  */
 private static Image image;
 
 /**
  * 写入图片的对象取得
  *
  * @return image 图片对象
  */
 public static Image getImage() {
  return image;
 }

 /**
  * 图片设定
  *
  * @param imagePath 图片的路径和文件名
  * @see (c://word//maggie.JPG)
  * @throws  DocumentException,IOException
  */
 public static Image setImage(String imagePath) throws DocumentException,IOException {
  WordGenerate.image = Image.getInstance(imagePath);
  return WordGenerate.image;
 }

 /**
  * 文档段落内容设定
  *
  * @param leading 行间设定
  * @param content 写入文档的设定
  * @throws DocumentException
  * @throws IOException
  * @return Paragraph
  */
 public static Paragraph setParagraph(float leading, String content) throws DocumentException,IOException {
  Paragraph paragraph = new Paragraph(leading,content);
  WordGenerate.paragraph = paragraph;
  return WordGenerate.paragraph;
 }

 /**
  * 文档段落内容设定
  *
  * @param leading 行间距
  * @param content 写入文档的内容
  * @param font 字体
  * @throws DocumentException
  * @throws IOException
  */
 public static Paragraph setParagraph(float leading, String content, Font font) throws DocumentException,IOException {
  Paragraph paragraph = new Paragraph(leading,content,font);
  WordGenerate.paragraph = paragraph;
  return WordGenerate.paragraph;
 }
 
 /**
  * 文档段落内容设定
  *
  * @param content 写入文档的内容
  * @throws DocumentException
  * @throws IOException
  */
 public static Paragraph setParagraph(String content) throws DocumentException,IOException {
  Paragraph paragraph = new Paragraph(content);
  WordGenerate.paragraph = paragraph;
  return WordGenerate.paragraph;
 }
 
 /**
  * 字体设定
  *
  * @fontFilePath 字体文件路径
  * @param fontSize 字体大小
  * @param fontStyle Font.NORMAL、Font.BOLD等作为参数设定
  */
 public static Font setFont(String fontFilePath,int fontSize, int fontStyle) throws DocumentException,IOException {
  
  // 设置中文字体
  bfChinese = BaseFont.createFont(fontFilePath ,BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
  
  // 标题字体风格
  WordGenerate.font = new Font(bfChinese, fontSize, fontStyle);
  return WordGenerate.font;
 }
 
 /**
  * 打开并生成文档
  * @param path 文档路径和文件名
  */
 public static Document OpenDoc(String path)throws DocumentException,IOException {
  document = new Document(getPageSize());
  RtfWriter2.getInstance(document, new FileOutputStream(path));
  document.open();
  return document;
 }
 
 /**
  * 取得文档打印纸A4、A3
  *
  * @return PageSize
  * @see com.lowagie.text.PageSize
  */
 public static Rectangle getPageSize() {
  return pageSize;
 }
 
 /**
  * 设定文档打印纸A4、A3
  * PageSize.A4 PageSize.A3作为参数设定
  * @param pageSize
  * @see com.lowagie.text.PageSize
  */
 public static void setPageSize(Rectangle pageSize) {
  WordGenerate.pageSize = pageSize;
 }
 
 /**
  * 关闭文档,文档使用完后必须关闭
  */
 public static void CloseDoc() {
  WordGenerate.document.close();
 }
}

3、测试文件

 

package cn.com.report.document.word;

import java.io.IOException;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;

/**
 * @author 岑
 *
 */
public class WordGenerateTest {


 /**
  * @param args
  */
 public static void main(String[] args) {
  try {

   WordGenerate.setPageSize(PageSize.A4);

// 生成的文件和路径名

   Document document = WordGenerate.OpenDoc("c://document//Test.doc");

//Document document = WordGenerate.OpenDoc("c://document//Test.rtf");
   
   Font titleFont = WordGenerate.setFont(WordGenerate.SIMFANG,16, Font.BOLD);
   
   // 添加标题
   String title = "标题";
   Paragraph titlePara = WordGenerate.setParagraph(title);
   titlePara.setAlignment(Element.ALIGN_CENTER);
   titlePara.setFont(titleFont);
   document.add(titlePara);

   // 添加文本内容
   String context = "在某些情况下,必须连接到 Internet 才能使用 SCW 帮助中的链接。如果您的计算机未连接到 Internet,那么可以通过搜索链接文本在“帮助和支持中心”中找到相同的主题。要打开“帮助和支持中心”,请单击“开始”,然后单击“帮助和支持中心”。"
           + "可以将 SCW 安装在运行带 SP1 的 Windows Server 2003 家族成员的计算机上。"
           + "有关如何充分利用 SCW 的建议,请参阅最佳操作。"
           +"有关如何执行某些任务的信息,请参阅如何。 "
           + "有关一般背景知识,请参阅概念。"
           + "您不需要运行 SCW 以帮助保护运行 Windows Small Business Server 2003 的计算机。Windows Small Business Server 2003 使用安装程序以及配置电子邮件和 Internet 连接向导中的默认设置来帮助保护您的服务器。"
           +"如果尚未运行配置电子邮件和 Internet 连接向导,则应该运行该向导以帮助保护您的服务器。"
           +"在运行 Windows Small Business Server 2003 的计算机上启动配置电子邮件和 Internet 连接向导:"
           +"单击“开始”,然后单击“服务器管理”。"
           +"在控制台树中,单击“Internet 和电子邮件”。"
           +"在详细信息窗格中,单击“连接到 Internet”。";
   Paragraph contextPara = WordGenerate.setParagraph(10,context);
   contextPara.setAlignment(Element.ALIGN_LEFT);
   Font contextFont = WordGenerate.setFont(WordGenerate.SIMFANG,10, Font.NORMAL);
   contextPara.setFont(contextFont);
   contextPara.setSpacingBefore(20);
   contextPara.setFirstLineIndent(20);
   document.add(contextPara);
   
   // 添加空行
   Paragraph contextSpeace = WordGenerate.setParagraph("");
   contextSpeace.setSpacingBefore(20);   
   document.add(contextSpeace);
   // 添加图片信息

  // 要插入的图片路径
   Image image = WordGenerate.setImage("c://document//maggie.JPG");
   image.setAlignment(Image.ALIGN_CENTER);
   document.add(image);

   WordGenerate.CloseDoc();
  } catch (DocumentException DocEx) {
   System.out.print(""+ DocEx.getMessage());
  } catch (IOException IOex) {
   System.out.print(""+ IOex.getMessage());
  }
 }
}

 

各位请多多指教,多多交流

msn:rejonsam@163.com