`

office工具类

    博客分类:
  • JAVA
阅读更多

将jcom.dll放入jdk的bin目录下,将jcom.jar放到项目里面,如果要实现pdf的转换,下载:

http://down2.cnzz.cc/soft/bigsoft/Acrobat_pro_812_cnzz.cc.rar
http://www.vichx.com/upload/Keygen.rar

工具类,实现了少量方法:

OfficeUtil.java:

 

import java.io.File;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jp.ne.so_net.ga2.no_ji.jcom.IDispatch;
import jp.ne.so_net.ga2.no_ji.jcom.JComException;
import jp.ne.so_net.ga2.no_ji.jcom.ReleaseManager;
import jp.ne.so_net.ga2.no_ji.jcom.excel8.ExcelApplication;
import jp.ne.so_net.ga2.no_ji.jcom.excel8.ExcelRange;
import jp.ne.so_net.ga2.no_ji.jcom.excel8.ExcelWorkbook;
import jp.ne.so_net.ga2.no_ji.jcom.excel8.ExcelWorkbooks;
import jp.ne.so_net.ga2.no_ji.jcom.excel8.ExcelWorksheet;
import jp.ne.so_net.ga2.no_ji.jcom.excel8.ExcelWorksheets;


/**
 * word、excel工具类
 * 
 * @author 陈均
 * 
 */
public class OfficeUtil {

	public static final String WORD_APP = "Word.Application";
	public static final String PDF_APP = "PDFMakerAPI.PDFMakerApp";
	public static final String VISIBLE = "Visible";
	public static final String DOCUMENTS = "Documents";
	public static final String OPEN = "Open";
	public static final String TABLES = "Tables";
	public static final String COUNT = "Count";
	public static final String COLUMNS = "Columns";
	public static final String ROWS = "rows";
	public static final String ITEM = "Item";
	public static final String CELL = "Cell";
	public static final String ADD = "Add";
	public static final String SELECTION = "Selection";
	public static final String RANGE = "range";
	public static final String TEXT = "Text";
	public static final String WIDTH = "Width";
	public static final String HEIGHT = "Height";
	public static final String SAVEAS = "saveAs";
	public static final String QUIT = "Quit";
	public static final String ACTIVEDOCUMENT = "ActiveDocument";

	public static final Boolean V_FALSE = new Boolean(false);
	public static final Boolean V_TRUE = new Boolean(true);
	public static final Integer REPLACE = new Integer(2);
	public static final Integer WRAP = new Integer(1);

	/**
	 * 将指定的excel数据映射成实体集合
	 * 
	 * @param filePath
	 *            excel文件的绝对路径
	 * @param fieldMap
	 *            对实体字段的映射描述
	 * @param clazz
	 *            映射的实体类型
	 * @return 实体集合结果
	 */
	public <T> List<T> excelMapEntity(String filePath,
			Map<String, String> fieldMap, Class<T> clazz) throws Exception {
		ReleaseManager rm = new ReleaseManager();
		ExcelApplication excel = new ExcelApplication(rm);
		excel.Visible(true);
		ExcelWorkbooks xlBooks = excel.Workbooks();
		ExcelWorkbook xlBook = xlBooks.Open(filePath);
		ExcelWorksheet xlSheet = excel.ActiveSheet();
		ExcelRange xlRange = xlSheet.Cells();
		int cols = 0;
		int rows = 0;
		for (int i = 1; i < 256; i++) {
			String fieldDesc = xlRange.Item(1, i).Text();
			if ("".equals(fieldDesc)) {
				cols = i - 1;
				break;
			}
		}
		Object fieldVal = "";// 字段值
		String fieldDesc = "";// 字段描述
		String fieldName = "";// 映射成类字段
		boolean end = false;// 是否行结束
		List<T> list = new ArrayList<T>();
		for (int i = 2; i < 65536; i++) {
			T entity = clazz.newInstance();
			for (int j = 1; j <= cols; j++) {
				fieldVal = xlRange.Item(i, j).Text();
				if ("".equals(fieldVal)) {
					end = true;
					break;
				}
				fieldDesc = xlRange.Item(1, j).Text();
				fieldName = fieldMap.get(fieldDesc);
				Field field = clazz.getDeclaredField(fieldName);
				Class<?> z = field.getType();
				field.setAccessible(true);
				if(z.newInstance() instanceof java.util.Date){
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					fieldVal = sdf.parse(fieldVal.toString());
				}
				field.set(entity, fieldVal);
			}
			if (end) {
				rows = i - 2;
				break;
			}
			list.add(entity);
		}
		System.out.println("实际行数:" + rows);
		System.out.println("实际列数:" + cols);
		xlBook.Close(false, null, false);
		excel.Quit();
		rm.release();
		return list;
	}

	/**
	 * 将指定的集合数据映射成excel数据文件
	 * 
	 * @param <T>
	 * @param list
	 *            数据集合
	 * @param saveFilePath
	 *            保存文件的绝对路径
	 * @param fieldMap
	 *            对实体字段的映射描述
	 * @param clazz
	 *            映射的实体类型
	 * @throws Exception
	 */
	public <T> void entityMapExcel(List<T> list, String saveFilePath,
			Map<String, String> fieldMap,List<String> fieldDescList, Class<T> clazz) throws Exception {
		ReleaseManager rm = new ReleaseManager();
		ExcelApplication excel = new ExcelApplication(rm);
		excel.Visible(true);
		ExcelWorkbooks xlBooks = excel.Workbooks();
		ExcelWorkbook xlBook = xlBooks.Add();
		ExcelWorksheets xlSheets = xlBook.Worksheets();
		ExcelWorksheet xlSheet = xlSheets.Item(1);
		ExcelRange xlRange = xlSheet.Cells();
		int rows = list.size();
		int cols = fieldMap.size();
		System.out.println("实际列数:" + cols);
		System.out.println("实际行数:" + rows);

		int index = 1;
		for (String item : fieldDescList) {
			xlRange.Item(1, index).Value(item);
			index++;
		}
		Object fieldVal = "";// 字段值
		String fieldDesc = "";// 字段描述
		String fieldName = "";// 映射成类字段
		// 生成具体内容
		for (int i = 1; i <= rows; i++) {
			T entity = list.get(i - 1);
			for (int j = 1; j <= cols; j++) {
				fieldDesc = xlRange.Item(1, j).Text();
				fieldName = fieldMap.get(fieldDesc);
				System.out.println(j + fieldDesc + "-->" + fieldName);
				Field field = clazz.getDeclaredField(fieldName);
				Class<?> z = field.getType();
				field.setAccessible(true);
				fieldVal = field.get(entity);
				if(z.newInstance() instanceof java.util.Date){
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					fieldVal = sdf.format(fieldVal);
				}
				if(fieldVal==null) fieldVal = "";
				xlRange.Item(i + 1, j).Value(fieldVal.toString());
			}
		}
		File file = new File(saveFilePath);
		if(file.exists()) file.delete();
		xlBook.SaveAs(saveFilePath);
		xlBook.Close(false, null, false);
		excel.Quit();
	}

	/**
	 * 将指定的word表格数据映射成实体集合
	 * 
	 * @param <T>
	 * @param filePath
	 *            word文件的绝对路径
	 * @param fieldMap
	 *            对实体字段的映射描述
	 * @param clazz
	 *            映射的实体类型
	 * @return 实体集合结果
	 * @throws Exception
	 */
	public <T> List<T> wordMapEntity(String filePath,
			Map<String, String> fieldMap, Class<T> clazz) throws Exception {
		ReleaseManager rm = new ReleaseManager();
		IDispatch wdApp = new IDispatch(rm, WORD_APP);
		wdApp.put(VISIBLE, new Boolean(true));
		IDispatch wdDocuments = (IDispatch) wdApp.get(DOCUMENTS);
		IDispatch wdDocument = (IDispatch) wdDocuments.method(OPEN,
				new Object[] { filePath });
		String fullname = (String) wdDocument.get("FullName");
		System.out.println("fullname=" + fullname);

		IDispatch wdTables = (IDispatch) wdDocument.get(TABLES);
		System.out.println(wdTables);
		Integer table_count = (Integer) wdTables.get(COUNT);
		System.out.println("表格数=" + table_count);

		IDispatch wdTable = (IDispatch) wdTables.method(ITEM,
				new Object[] { new Integer(1) });
		IDispatch tableRows = (IDispatch) wdTable.get(ROWS);
		IDispatch tablecols = (IDispatch) wdTable.get(COLUMNS);
		Integer rows = (Integer) tableRows.get(COUNT);
		Integer cols = (Integer) tablecols.get(COUNT);
		System.out.println("表格行数:" + rows);
		System.out.println("表格列数:" + cols);
		Object fieldVal = "";// 字段值
		String fieldDesc = "";// 字段描述
		String fieldName = "";// 映射成类字段
		List<T> list = new ArrayList<T>();
		for (int i = 2; i <= rows; i++) {
			T entity = clazz.newInstance();
			for (int j = 1; j <= cols; j++) {
				IDispatch cell = (IDispatch) wdTable.method(CELL, new Object[] {
						new Integer(1), new Integer(j) });
				IDispatch range = (IDispatch) cell.get("Range");
				fieldDesc = range.get("Text").toString();
				fieldDesc = fieldDesc.substring(0, fieldDesc.length() - 2);

				IDispatch FieldCell = (IDispatch) wdTable.method(CELL,
						new Object[] { new Integer(i), new Integer(j) });
				IDispatch FieldRange = (IDispatch) FieldCell.get("Range");
				fieldVal = FieldRange.get("Text");
				fieldVal = fieldVal.toString().substring(0, fieldVal.toString().length() - 2);
				fieldName = fieldMap.get(fieldDesc);
				Field field = clazz.getDeclaredField(fieldName);
				field.setAccessible(true);
				Class<?> z = field.getType();
				if(z.newInstance() instanceof java.util.Date){
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					fieldVal = sdf.parse(fieldVal.toString());
				}
				field.set(entity, fieldVal);
				// System.out.println("字段描述:" + fieldDesc + ";字段名字:" +fieldName
				// + ";字段值:" + fieldVal);
			}

			list.add(entity);
		}
		wdApp.method(QUIT, null);
		rm.release();
		return list;
	}

	/**
	 * 将指定的集合数据映射成word数据文件
	 * 
	 * @param <T>
	 * @param list
	 *            数据集合
	 * @param saveFilePath
	 *            保存文件的绝对路径
	 * @param fieldMap
	 *            对实体字段的映射描述
	 * @param clazz
	 *            映射的实体类型
	 * @throws Exception
	 */
	public <T> void entityMapWord(List<T> list, String saveFilePath,
			Map<String, String> fieldMap,List<String> fieldDescList, Class<T> clazz) throws Exception {
		ReleaseManager rm = new ReleaseManager();
		IDispatch wdApp = new IDispatch(rm, WORD_APP);
		wdApp.put(VISIBLE, new Boolean(true));
		IDispatch wdDocuments = (IDispatch) wdApp.get(DOCUMENTS);
		IDispatch wdDocument = (IDispatch) wdDocuments.method(ADD, null);
		IDispatch wdTables = (IDispatch) wdDocument.get(TABLES);
		Integer table_count = (Integer) wdTables.get(COUNT);
		System.out.println("表格数=" + table_count);
		Integer rows = list.size();
		Integer cols = fieldMap.size();
		System.out.println("实际列数:" + cols);
		System.out.println("实际行数:" + rows);
		IDispatch selection = (IDispatch) wdApp.get(SELECTION);
		IDispatch wdTable = (IDispatch) wdTables.method(ADD, new Object[] {
				selection.get(RANGE), rows + 1, cols });
		// 生成头描述
		int index = 1;
		for (String item : fieldDescList) {
			IDispatch cell = (IDispatch) wdTable.method(CELL, new Object[] {
					new Integer(1), new Integer(index) });
			IDispatch range = (IDispatch) cell.get("Range");
			range.put(TEXT, item);
			index++;
		}

		Object fieldVal = "";// 字段值
		String fieldDesc = "";// 字段描述
		String fieldName = "";// 映射成类字段

		for (int i = 1; i <= rows; i++) {
			T entity = list.get(i - 1);
			System.out.println("***********************");
			for (int j = 1; j <= cols; j++) {
				IDispatch cell = (IDispatch) wdTable.method(CELL, new Object[] {
						new Integer(1), new Integer(j) });
				IDispatch range = (IDispatch) cell.get("Range");
				fieldDesc = range.get("Text").toString();
				fieldDesc = fieldDesc.substring(0, fieldDesc.length() - 2);
				fieldName = fieldMap.get(fieldDesc);
				Field field = clazz.getDeclaredField(fieldName);
				field.setAccessible(true);
				fieldVal = field.get(entity);
				Class<?> z = field.getType();
				if(z.newInstance() instanceof java.util.Date){
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					fieldVal = sdf.format(fieldVal);
				}
				if(fieldVal==null) fieldVal = "";
				
				IDispatch FieldCell = (IDispatch) wdTable.method(CELL,
						new Object[] { new Integer(i + 1), new Integer(j) });
				IDispatch FieldRange = (IDispatch) FieldCell.get("Range");
				FieldRange.put(TEXT, fieldVal);
				System.out.println("字段描述:" + fieldDesc + ";字段名字:" + fieldName
						+ ";字段值:" + fieldVal);
			}
		}
		((IDispatch) wdApp.get(ACTIVEDOCUMENT)).method(SAVEAS,
				new Object[] { saveFilePath, new Integer(0) });
		wdApp.method(QUIT, null);
		rm.release();
	}

	/**
	 * 文件转pdf文件
	 * 
	 * @throws Exception
	 */
	public void fileToPdf(String filePath, String pdfPath) throws Exception {
		ReleaseManager rm = new ReleaseManager();
		IDispatch pdfApp = new IDispatch(rm, PDF_APP);
		Object result = pdfApp.method("CreatePDF", new Object[] { filePath, pdfPath });
		System.out.println(result);
		rm.release();
	}

	/** 合并WORD文档,第一个为要合并的文档* */
	public static void uniteDoc(List<String> fileList, String saveFilePath)throws Exception {
		if (fileList.size() == 0 || fileList == null) {
			return;
		}
		ReleaseManager rm = new ReleaseManager();
		IDispatch wdApp = new IDispatch(rm, WORD_APP);
		wdApp.put(VISIBLE, new Boolean(true));
		try {
			IDispatch wdDocuments = (IDispatch) wdApp.get(DOCUMENTS);
			wdDocuments.method(OPEN,new Object[] { fileList.get(0) });
			for (int i = 1; i < fileList.size(); i++) {
				IDispatch selection = (IDispatch) wdApp.get(SELECTION);
				selection.method("HomeKey", new Object[]{new Integer(6)});
				selection.method("insertFile", new Object[]{fileList.get(i),"",V_FALSE,V_FALSE,V_FALSE});
			}
			((IDispatch) wdApp.get("ActiveDocument")).method("saveAs",
					new Object[] { saveFilePath, new Integer(0) });
		} catch (Exception e) {
			throw new RuntimeException("合并word文件出错.原因:" + e);
		} finally {
			wdApp.method(QUIT, null);
			rm.release();
		}
	}
	/**
	 * 在指定的word文件的位置插入一张指定大小的图片
	 * 
	 * @param filePath
	 *            word文件的绝对路径
	 * @param imagePath
	 *            图片的绝对路径
	 * @param w
	 *            图片在word中的宽度
	 * @param h
	 *            图片在word中高度
	 * @param x
	 *            图片在word中的x坐标
	 * @param y
	 *            图片在word中的y坐标
	 * @throws Exception
	 */
	public void insertImage(String filePath, String imagePath, Integer w,
			Integer h, Integer x, Integer y) throws Exception {
		ReleaseManager rm = new ReleaseManager();
		IDispatch wdApp = new IDispatch(rm, WORD_APP);
		wdApp.put(VISIBLE, new Boolean(true));
		IDispatch wdDocuments = (IDispatch) wdApp.get(DOCUMENTS);
		wdDocuments.method(OPEN, new Object[] { filePath });
		IDispatch selection = (IDispatch) wdApp.get(SELECTION);
		IDispatch inlineShapes = (IDispatch) selection.get("InlineShapes");
		IDispatch image = (IDispatch) inlineShapes.method("AddPicture",
				new Object[] { imagePath });
		image.put(WIDTH, w);
		image.put(HEIGHT, h);
		IDispatch shape = (IDispatch) image.method("ConvertToShape", null);
		shape.method("IncrementLeft", new Object[] { x });
		shape.method("IncrementTop", new Object[] { y });
		IDispatch activeDoc = (IDispatch) wdApp.get(ACTIVEDOCUMENT);
		activeDoc.method("Save", null);
		wdApp.method(QUIT, null);
		rm.release();
	}

	
	/**
	 * 批量替换doc里面的内容
	 * 
	 * @param filePath
	 *            word文件的绝对路径
	 * @param saveFilePath
	 *            替换后的文件存放的绝对路径
	 * @param params替换的内容
	 * @param fileParams 文件占位符替换
	 * @throws Exception
	 */
	public void batchReplace(String filePath, String saveFilePath,
			Map<String, String> params,Map<String, String[]> fileParams) throws Exception {
		ReleaseManager rm = new ReleaseManager();
		IDispatch wdApp = new IDispatch(rm, WORD_APP);
		try {
			wdApp.put(VISIBLE, new Boolean(true));
			IDispatch wdDocuments = (IDispatch) wdApp.get(DOCUMENTS);
			wdDocuments.method(OPEN, new Object[] { filePath });
			IDispatch selection = (IDispatch) wdApp.get(SELECTION);
			IDispatch find = (IDispatch) selection.get("Find");
			find.method("ClearFormatting", null);
			IDispatch replacement = (IDispatch) find.get("Replacement");
			replacement.method("ClearFormatting", null);

			for (String findText : params.keySet()) {
				String replaceText = params.get(findText);
				if(replaceText==null)replaceText = "";
					if(replaceText.length()>200){
						int len = replaceText.length();
						while(len != -1){
							if(len>200){
								String tmpreplaceText = replaceText.substring(0,200);
								replaceText = replaceText.substring(200);
								len = replaceText.length();
								find.method("Execute", new Object[] { findText, V_TRUE, V_FALSE,
										V_FALSE, V_FALSE, V_FALSE, V_TRUE, WRAP, V_FALSE,
										tmpreplaceText+findText,REPLACE });
							}else{
								replaceText = replaceText.substring(0,len);
								len = -1;
								find.method("Execute", new Object[] { findText, V_TRUE, V_FALSE,
										V_FALSE, V_FALSE, V_FALSE, V_TRUE, WRAP, V_FALSE,
										replaceText,REPLACE });
							}
						}
						
					}else{
						find.method("Execute", new Object[] { findText, V_TRUE, V_FALSE,
								V_FALSE, V_FALSE, V_FALSE, V_TRUE, WRAP, V_FALSE,
								replaceText,REPLACE });
					}
					
			}
			
			for (String findText : fileParams.keySet()) {
				String imagePath = fileParams.get(findText)[0];
				String w = fileParams.get(findText)[1];
				String h = fileParams.get(findText)[2];
				find.method("ClearFormatting", null);
				find.put(TEXT, findText);
				find.put("Forward", "True");
				find.put("Format", "True");
				find.put("MatchCase", "True");
				find.put("MatchWholeWord", "True");
				find.method("Execute", null);
				IDispatch inlineShapes = (IDispatch) selection.get("InlineShapes");
				IDispatch image = (IDispatch) inlineShapes.method("AddPicture",
						new Object[] { imagePath });
				if(w!=null && !"".equals(w))
				image.put(WIDTH, w);
				if(h!=null && !"".equals(h))
				image.put(HEIGHT, h);
			}
			
			IDispatch activeDoc = (IDispatch) wdApp.get(ACTIVEDOCUMENT);
			activeDoc.method(SAVEAS, new Object[] { saveFilePath, new Integer(0) });
		} catch (Exception e) {
			throw e;
		}finally{
			System.out.println("退出程序.........");
			wdApp.method(QUIT, null);
			rm.release();
		}
	}
	
	/**
	 * 批量替换doc里面的内容
	 * 
	 * @param filePath
	 *            word文件的绝对路径
	 * @param saveFilePath
	 *            替换后的文件存放的绝对路径
	 * @param params替换的内容
	 * @throws Exception
	 */
	public void batchReplace(String filePath, String saveFilePath,
			Map<String, String> params) throws Exception {
		ReleaseManager rm = new ReleaseManager();
		IDispatch wdApp = new IDispatch(rm, WORD_APP);
		wdApp.put(VISIBLE, new Boolean(true));
		IDispatch wdDocuments = (IDispatch) wdApp.get(DOCUMENTS);
		wdDocuments.method(OPEN, new Object[] { filePath });
		IDispatch selection = (IDispatch) wdApp.get(SELECTION);
		IDispatch find = (IDispatch) selection.get("Find");
		find.method("ClearFormatting", null);
		IDispatch replacement = (IDispatch) find.get("Replacement");
		replacement.method("ClearFormatting", null);

		for (String findText : params.keySet()) {
			String replaceText = params.get(findText);
			if(replaceText==null)replaceText = "";
			find.method("Execute", new Object[] { findText, V_TRUE, V_FALSE,
						V_FALSE, V_FALSE, V_FALSE, V_TRUE, WRAP, V_FALSE,
						replaceText,REPLACE });

		}
		IDispatch activeDoc = (IDispatch) wdApp.get(ACTIVEDOCUMENT);
		activeDoc.method(SAVEAS, new Object[] { saveFilePath, new Integer(0) });
		wdApp.method(QUIT, null);
		rm.release();
	}
	

	public static void testBatchReplace() throws Exception {
		OfficeUtil officeUtil = new OfficeUtil();
		String filePath = "e:\\template.doc";
		String saveFilePath = "e:\\test.doc";
		Map<String, String> params = new HashMap<String, String>();
		//params.put("#DISTRIBUTECHAR#", "forever");
		params.put("#IP_NAME#", "chenjun");
		
		
		//TypeParagraph
		officeUtil.batchReplace(filePath, saveFilePath, params);
	}

	public static void testInsertImage() throws Exception {
		OfficeUtil officeUtil = new OfficeUtil();
		String filePath = "e:\\Users_save.doc";
		String imagePath = "e:\\b.jpg";
		officeUtil.insertImage(filePath, imagePath, 100, 100, 200, 400);
	}

	public static void testFileToPdf() throws Exception {
		OfficeUtil officeUtil = new OfficeUtil();
		String wordPath = "e:\\template.doc";
		String pdfPath = "e:\\users.pdf";
		officeUtil.fileToPdf(wordPath, pdfPath);
	}

	public static void main(String[] args)throws Exception {
		//testBatchReplace();
		String wordPath = "e:\\template.doc";
		ReleaseManager rm = new ReleaseManager();
		IDispatch wdApp = new IDispatch(rm, OfficeUtil.WORD_APP);
		wdApp.put(OfficeUtil.VISIBLE, new Boolean(true));
		IDispatch wdDocuments = (IDispatch) wdApp.get(OfficeUtil.DOCUMENTS);
		IDispatch wdDocument = (IDispatch) wdDocuments.method(OfficeUtil.OPEN,
				new Object[] { wordPath });
		IDispatch wdTables = (IDispatch) wdDocument.get(OfficeUtil.TABLES);
		
		System.out.println(wdTables.get(COUNT));
		//testEntityMapExcel();
		//testExcelMapEntity();
		//testEntityMapWord();
		//testWordMapEntity();
		
		//testInsertImagePos();
		//wrapFormat.method("ZOrder",new Object[]{new Integer(4)});
//		String filePath = "e:\\信息.doc";
//		ReleaseManager rm = new ReleaseManager();
//		IDispatch wdApp = new IDispatch(rm, WORD_APP);
//		wdApp.put(VISIBLE, new Boolean(true));
//		IDispatch wdDocuments = (IDispatch) wdApp.get(DOCUMENTS);
//		IDispatch wdDocument = (IDispatch) wdDocuments.method(OPEN,
//				new Object[] { filePath });
//		String fullname = (String) wdDocument.get("FullName");
//		System.out.println("fullname=" + fullname);
//
//		IDispatch wdTables = (IDispatch) wdDocument.get(TABLES);
//		Integer table_count = (Integer) wdTables.get(COUNT);
//		System.out.println("表格数=" + table_count);
//		IDispatch wdTable = (IDispatch) wdTables.method(ITEM,
//				new Object[] { new Integer(1) });
//		IDispatch tableRows = (IDispatch) wdTable.get(ROWS);
//		IDispatch tablecols = (IDispatch) wdTable.get(COLUMNS);
//		Float w = (Float)wdTable.get("PreferredWidth");
//		System.out.println(w);
//		Integer rows = (Integer) tableRows.get(COUNT);
//		Integer cols = (Integer) tablecols.get(COUNT);
//		System.out.println("表格行数:" + rows);
//		System.out.println("表格列数:" + cols);
//		String fieldDesc = "";
//		StringBuffer sb = new StringBuffer("<table width=\"439\" height=\"140\" border=\"1\">");
//		for(int i = 1;i<=rows;i++){
//			System.out.println("*****************");
//			sb.append("<tr>");
//			for(int j = 1;j<=cols;j++){
//				IDispatch cell = (IDispatch) wdTable.method(CELL, new Object[] {
//						new Integer(i), new Integer(j) });
//				IDispatch range = (IDispatch) cell.get(RANGE);
//				fieldDesc = range.get(TEXT).toString();
//				fieldDesc = fieldDesc.substring(0, fieldDesc.length() - 2);
//				//根据字段类型生成相应内容
//				sb.append(" <td>#text#</td>".replaceAll("#text#", fieldDesc));
//				//System.out.println(fieldDesc);
//			}
//			sb.append("</tr>");
//		}
//		sb.append("</table>");
//		System.out.println(sb.toString());
		//testFileToPdf();
		
		
		
		
	}

	public static void testInsertImagePos() throws JComException {
		String filePath = "e:\\template.doc";
		String imagePath = "e:\\chenjun.PNG";
		ReleaseManager rm = new ReleaseManager();
		IDispatch wdApp = new IDispatch(rm, OfficeUtil.WORD_APP);
		wdApp.put(OfficeUtil.VISIBLE, new Boolean(true));
		IDispatch wdDocuments = (IDispatch) wdApp.get(OfficeUtil.DOCUMENTS);
		IDispatch wdDocument = (IDispatch) wdDocuments.method(OfficeUtil.OPEN,
				new Object[] { filePath });
		IDispatch selection = (IDispatch) wdApp.get(SELECTION);
		IDispatch find = (IDispatch) selection.get("Find");
		find.put(TEXT, "#qm#");
		find.put("Forward", "True");
		find.put("Format", "True");
		find.put("MatchCase", "True");
		find.put("MatchWholeWord", "True");
		Object obj = find.method("Execute", null);
		System.out.println(obj);
		IDispatch inlineShapes = (IDispatch) selection.get("InlineShapes");
		IDispatch image = (IDispatch) inlineShapes.method("AddPicture",
				new Object[] { imagePath });
		//image.put(WIDTH, 100);
		//image.put(HEIGHT, 100);
		IDispatch shape = (IDispatch) image.method("ConvertToShape", null);
		
		IDispatch wrapFormat = (IDispatch) shape.get("WrapFormat");
		wrapFormat.put("Type", new Integer(3));
		
		
	}

	public static void testInsertRow() throws JComException {
		String filePath = "e:\\20100802114149518.doc";
		String saveFilePath = "e:\\201008021141495182.doc";
		ReleaseManager rm = new ReleaseManager();
		IDispatch wdApp = new IDispatch(rm, OfficeUtil.WORD_APP);
		wdApp.put(OfficeUtil.VISIBLE, new Boolean(true));
		IDispatch wdDocuments = (IDispatch) wdApp.get(OfficeUtil.DOCUMENTS);
		IDispatch wdDocument = (IDispatch) wdDocuments.method(OfficeUtil.OPEN,
				new Object[] { filePath });
		String fullname = (String) wdDocument.get("FullName");
		System.out.println("fullname=" + fullname);

		IDispatch wdTables = (IDispatch) wdDocument.get(OfficeUtil.TABLES);
		System.out.println(wdTables);
		Integer table_count = (Integer) wdTables.get(OfficeUtil.COUNT);
		System.out.println("表格数=" + table_count);

		IDispatch wdTable = (IDispatch) wdTables.method(OfficeUtil.ITEM,
				new Object[] { new Integer(1) });
		IDispatch tableRows = (IDispatch) wdTable.get(OfficeUtil.ROWS);
		IDispatch tablecols = (IDispatch) wdTable.get(OfficeUtil.COLUMNS);
		Integer rows = (Integer) tableRows.get(OfficeUtil.COUNT);
		Integer cols = (Integer) tablecols.get(OfficeUtil.COUNT);
		
		String fieldDesc = "";
		Map<String, Integer> fieldPos = new HashMap<String, Integer>();
		for(int i=1;i<=cols;i++){
			IDispatch cell = (IDispatch) wdTable.method(OfficeUtil.CELL, new Object[] {
					new Integer(2), new Integer(i) });
			IDispatch range = (IDispatch) cell.get(RANGE);
			fieldDesc = range.get(TEXT).toString();
			fieldDesc = fieldDesc.substring(0, fieldDesc.length() - 2);
			System.out.println(fieldDesc);
			if(!"".equals(fieldDesc)){
				fieldPos.put(fieldDesc, new Integer(i));
			}
		}
		System.out.println(fieldPos.size());
		for(int i = 3;i<=4;i++){
			IDispatch lastRow = (IDispatch) tableRows.method(ITEM, new Object[]{i-1});
			tableRows.method(ADD, new Object[]{lastRow});
			rows++;
			for (int j = 1; j <= cols; j++) {
				IDispatch cell = (IDispatch) wdTable.method(OfficeUtil.CELL, new Object[] {
						new Integer(rows), new Integer(j) });
				IDispatch range = (IDispatch) cell.get(RANGE);
				fieldDesc = range.get(TEXT).toString();
				fieldDesc = fieldDesc.substring(0, fieldDesc.length() - 2);
				if(!"".equals(fieldDesc)){
					IDispatch FieldCell = (IDispatch) wdTable.method(OfficeUtil.CELL,
							new Object[] { new Integer(rows-1), new Integer(j) });
					IDispatch FieldRange = (IDispatch) FieldCell.get(RANGE);
					FieldRange.put(OfficeUtil.TEXT, "数据");
				}
			}
		}
		//删除最后一行
		IDispatch lastRow = (IDispatch) tableRows.method(ITEM, new Object[]{rows});
		lastRow.method("Delete",null);
		System.out.println("表格行数:" + rows);
		System.out.println("表格列数:" + cols);
		((IDispatch) wdApp.get(ACTIVEDOCUMENT)).method(SAVEAS,
				new Object[] { saveFilePath, new Integer(0) });
		wdApp.method(OfficeUtil.QUIT, null);
		rm.release();
	}

}

 

 

0
2
分享到:
评论

相关推荐

    Android的Office工具类

    "Android的Office工具类"主要关注如何在Android环境中实现对这些常见办公格式的支持。本文将深入探讨Android开发中处理Office和PDF文档的关键知识点。 1. **Android POI库**: 压缩包中的“android-poi”可能是指...

    java office转pdf工具类

    Java Office转PDF工具类是Java开发中用于将Office文档转换为PDF格式的一种解决方案。在Java环境中,Aspose是一个流行的库,提供了丰富的API来处理各种办公文档格式,包括Word、Excel、PowerPoint等,并且能够方便地...

    C#常用工具类代码集合Util第二版本(自己工作总结)

    C#常用工具类代码集合Util第二版本(自己工作总结),包括常用工具类,扩展方法工具类,百度地图C#工具类,Echart工具类,Office工具类,Autofac工具类,Web开发常用工具类,Winform开发常用工具类,是自己工作十年...

    Excel POI 工具类

    本篇将深入探讨"Excel POI 工具类",这个工具类旨在简化日常的Excel操作,提升开发效率。 Apache POI 提供了HSSF(Horizontally Stored Sheets Format)和XSSF(XML Spreadsheet Format)两个主要的API,分别用于...

    java mail工具类

    这个工具类的创建旨在简化邮件处理的复杂性,使开发者能够便捷地集成邮件功能。以下是对JavaMail工具类及其相关知识点的详细说明: 1. **JavaMail API**: JavaMail API 是Java平台上的标准邮件接口,提供了发送、...

    Excel导出工具类

    在IT行业中,Excel导出工具类是经常被用于数据处理和报表生成的模块。这个工具类通常是为了简化从应用程序中批量导出数据到Excel文件的过程,使得开发者可以更高效地处理大量的结构化信息。以下是对"Excel导出工具类...

    Office转PDF工具

    该工具是针对office转换为pdf开发的,相关的jar包都包含在其中,需要配置的文件也已经打包在压缩文件中,如果不知道如何进行操作,其中附有说明文件,代码都已经正常测试通过了。

    office卸载残留清理工具

    这类工具通常是为了帮助用户完全移除Office套件,解决因卸载不彻底导致的新安装问题或系统性能下降。 在描述中提到的“office卸载残留清理工具”,暗示可能在卸载Office后,用户遇到了一些问题,如新的Office版本...

    按模板导出Word工具类

    按模板导出Word工具类

    office清理工具.rar

    在使用这类工具时,用户通常需要按照以下步骤操作: 1. 首先,确保已经关闭所有运行中的Office应用程序,因为卸载过程中需要访问Office的相关文件。 2. 解压“Office清理工具.rar”到一个安全的位置,如桌面或文档...

    poi工具类poi导出表格的工具类

    本教程将深入探讨如何使用Apache POI工具类来高效地导出Excel表格。 **1. Apache POI的基本概念** Apache POI 提供了HSSF(Horizontally-Scattered Stream Format)和XSSF(XML Spreadsheet Format)两个主要的API...

    Office官方卸载工具

    "o15-ctrremove.diagcab"是这个卸载工具的文件名,其中"o15"代表Office 2013或Office 2016,"ctrremove"意味着它是一个用于移除Click-to-Run(C2R)版本的Office的工具,这是一种Office的部署技术,允许用户快速启动...

    Silverlight模拟Office工具栏源码

    这个“Silverlight模拟Office工具栏源码”项目,旨在为Web应用程序提供一个与Microsoft Office界面相似的工具栏,增强用户在网页上的文本编辑体验。 首先,我们来详细探讨Silverlight技术。Silverlight支持多媒体、...

    office2013卸载工具,能完全卸载

    需要注意的是,虽然这类卸载工具通常很有效,但并非100%保证每次都能成功解决问题。如果在使用后仍然无法安装新的Office版本,可能需要检查系统的其他问题,如系统权限、硬盘空间、兼容性等。 总的来说,"Office...

    java中poi读写excel封装工具类(兼容office2003和2007等版本)

    以下是对"java中poi读写excel封装工具类"这一主题的详细解释。 1. **Apache POI介绍** Apache POI是一个开源项目,允许Java开发者创建、修改和显示Microsoft Office文件,包括Excel、Word和PowerPoint。它的核心...

    java写的excel万能工具类

    Java编写的Excel万能工具类是一种高效处理Excel数据的实用程序,它可以帮助开发者轻松地读取、写入和操作Excel文件。在这个工具类中,通常会包含一系列静态方法,用于处理各种Excel相关的任务,比如打开文件、读取...

    win10 office 365卸载工具

    "win10 office 365卸载工具"就是针对这一需求设计的,它提供了便捷的一键卸载功能,能够帮助用户彻底移除Office 365组件,避免传统方法中可能出现的残留文件或注册表项。 通常,Windows系统内置的“程序和功能”...

    工具类

    在IT行业中,工具类是程序员日常开发中不可或缺的一部分。这些工具类通常包含了各种实用方法,以简化特定任务的处理,提高代码的复用性。在这个压缩包中,我们看到几个关键的Java工具类,分别是`POIExcelUtils.java`...

    office官方卸载工具

    "Office官方卸载工具"就是为了应对这类问题而设计的。 首先,我们要了解为何常规卸载方法可能失效。在GOST还原的操作系统中,由于系统还原点的影响,可能会影响到Office的卸载过程。此外,Office在安装过程中会在...

Global site tag (gtag.js) - Google Analytics