`

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
分享到:
评论

相关推荐

    课程设计基于python+mediapipe+opencv开发的手势识别系统源码(含超详细注释).zip

    课程设计基于python+mediapipe+opencv开发的手势识别系统源码(含超详细注释).zip个人经导师指导并认可通过的98分大作业设计项目,适用人群:计算机,电子信息工程、数学等专业的大学生课程设计、期末大作业或毕业设计,作为“参考资料”使用。 课程设计基于python+mediapipe+opencv开发的手势识别系统源码(含超详细注释).zip个人经导师指导并认可通过的98分大作业设计项目,适用人群:计算机,电子信息工程、数学等专业的大学生课程设计、期末大作业或毕业设计,作为“参考资料”使用。 课程设计基于python+mediapipe+opencv开发的手势识别系统源码(含超详细注释).zip个人经导师指导并认可通过的98分大作业设计项目,适用人群:计算机,电子信息工程、数学等专业的大学生课程设计、期末大作业或毕业设计,作为“参考资料”使用。 课程设计基于python+mediapipe+opencv开发的手势识别系统源码(含超详细注释).zip个人经导师指导并认可通过的98分大作业设计项目,适用人群:计算机,电子信息工程、数学等专业的大学生课程设计。

    yolov7 车牌检测 车牌识别 中文车牌识别 检测 支持双层车牌 支持12种中文车牌

    yolov7

    基于MQTT的智能宠物投喂系统.zip

    基于MQTT的智能宠物投喂系统:STM32、ESP8266、LCDST7789、压力传感器、按键中断修改定时投喂时间、云平台

    Qt进阶:优秀QT开源项目

    详细说明:https://blog.csdn.net/u010168781/article/details/138924179 1、Krita 2、QGIS 3、Kdenlive 4、Clementine 5、Syncthing 6、KDevelop

    2023-04-06-项目笔记 - 第一百三十四阶段 - 4.4.2.132全局变量的作用域-132 -2024.05.15

    2023-04-06-项目笔记-第一百三十四阶段-课前小分享_小分享1.坚持提交gitee 小分享2.作业中提交代码 小分享3.写代码注意代码风格 4.3.1变量的使用 4.4变量的作用域与生命周期 4.4.1局部变量的作用域 4.4.2全局变量的作用域 4.4.2.1全局变量的作用域_1 4.4.2.132全局变量的作用域_132 - 2024-05-15

    matlab基于区间知识的大脑情绪学习算法.zip

    matlab基于区间知识的大脑情绪学习算法.zip

    Scrapy-0.8.win32.exe

    文件操作、数据分析和网络编程等。Python社区提供了大量的第三方库,如NumPy、Pandas和Requests,极大地丰富了Python的应用领域,从数据科学到Web开发。Python库的丰富性是Python成为最受欢迎的编程语言之一的关键原因之一。这些库不仅为初学者提供了快速入门的途径,而且为经验丰富的开发者提供了强大的工具,以高效率、高质量地完成复杂任务。例如,Matplotlib和Seaborn库在数据可视化领域内非常受欢迎,它们提供了广泛的工具和技术,可以创建高度定制化的图表和图形,帮助数据科学家和分析师在数据探索和结果展示中更有效地传达信息。

    setuptools-34.1.0-py2.py3-none-any.whl

    文件操作、数据分析和网络编程等。Python社区提供了大量的第三方库,如NumPy、Pandas和Requests,极大地丰富了Python的应用领域,从数据科学到Web开发。Python库的丰富性是Python成为最受欢迎的编程语言之一的关键原因之一。这些库不仅为初学者提供了快速入门的途径,而且为经验丰富的开发者提供了强大的工具,以高效率、高质量地完成复杂任务。例如,Matplotlib和Seaborn库在数据可视化领域内非常受欢迎,它们提供了广泛的工具和技术,可以创建高度定制化的图表和图形,帮助数据科学家和分析师在数据探索和结果展示中更有效地传达信息。

    基于python+PyQt5开发的智能照明控制系统上位机软件源码.zip

    基于python+PyQt5开发的智能照明控制系统上位机软件源码.zip

    pytest-4.6.3.tar.gz

    文件操作、数据分析和网络编程等。Python社区提供了大量的第三方库,如NumPy、Pandas和Requests,极大地丰富了Python的应用领域,从数据科学到Web开发。Python库的丰富性是Python成为最受欢迎的编程语言之一的关键原因之一。这些库不仅为初学者提供了快速入门的途径,而且为经验丰富的开发者提供了强大的工具,以高效率、高质量地完成复杂任务。例如,Matplotlib和Seaborn库在数据可视化领域内非常受欢迎,它们提供了广泛的工具和技术,可以创建高度定制化的图表和图形,帮助数据科学家和分析师在数据探索和结果展示中更有效地传达信息。

    麦肯锡战略咨询经验.ppt

    麦肯锡战略咨询经验.ppt

    Redis入门基础篇+源码(springboot、maven)

    Redis入门基础篇-源码

    基于Python+flask+echarts实现的天气展示系统源码.zip

    基于Python+flask+echarts实现的天气展示系统源码.zip

    人工水母优化算法JS MATLAB源码, 应用案例为函数极值求解以及优化svm进行分类,代码注释详细,可结合自身需求进行应用

    人工水母优化算法JS MATLAB源码, 应用案例为函数极值求解以及优化svm进行分类,代码注释详细,可结合自身需求进行应用

    pytest-3.2.5.tar.gz

    文件操作、数据分析和网络编程等。Python社区提供了大量的第三方库,如NumPy、Pandas和Requests,极大地丰富了Python的应用领域,从数据科学到Web开发。Python库的丰富性是Python成为最受欢迎的编程语言之一的关键原因之一。这些库不仅为初学者提供了快速入门的途径,而且为经验丰富的开发者提供了强大的工具,以高效率、高质量地完成复杂任务。例如,Matplotlib和Seaborn库在数据可视化领域内非常受欢迎,它们提供了广泛的工具和技术,可以创建高度定制化的图表和图形,帮助数据科学家和分析师在数据探索和结果展示中更有效地传达信息。

    四旋翼双环pid控制matlab版本R2020b源码.zip

    四旋翼双环pid控制matlab版本R2020b源码.zip

    1-3.py

    1-3

    基于YOLOV5部署性能比较 opencvDNN、ONNX onnxruntime Openvion源码.zip

    基于YOLOV5部署性能比较 opencvDNN、ONNX onnxruntime Openvion源码.zip

    第五次作业答案.zip

    第五次作业答案.zip

Global site tag (gtag.js) - Google Analytics