java调用vbs,实现打开关闭excel操作小示例

文章本身没有多少技术含量。我本人一直不熟悉windows系统/脚本的东西。做WebDynPro开发时,碰到一个问题。里面的 office control不能加载POI生成的Excel。问了下SAP的人,他们说:我们不支持开源工具生成的excel。 我们只能绕路了。用 POI生成Excel,用Excel打开一下,保存一下,然后关闭,什么也做修改,office 控件就能加载这个excel了。在windows专区发了帖子,问了下批处理或者vbs能否做这样的事情。于是,就写了这么个例子。

 

/** * @Title: CallVbs.java * @Package vbs * @Description: TODO(用一句话描述该文件做什么) * @author youjianbo * @date 2011-3-8 下午04:14:50 * @version V1.0 */ package vbs; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class CallVbs { /** * @param args */ public static void main(String[] args) { try { // --获取指定目录下,所有excel文件名 List fileNameList = new ArrayList(); String dirName = "D://vbs"; File dir = new File(dirName); File[] files = dir.listFiles(); if (files == null) { System.out.println("当前目录没有文件"); return; } for (int i = 0; i < files.length; i++) { if (!files[i].isDirectory()) { String strFileName = files[i].getName(); if(strFileName.endsWith("xls")) { //System.out.println(strFileName); fileNameList.add(strFileName); } } } //--动态生成VBS文件。然后调用这些VBS文件,打开并保存excel文件 if(fileNameList.size()>0) { for(int i=0;i<fileNameList.size();i++) { String excelname = fileNameList.get(i).toString(); String FileName = dirName+"//vbs"+i+".vbs"; File vbsFile = new File(FileName); if(vbsFile.exists()){ vbsFile.delete(); //System.out.println("删除:"+FileName); } vbsFile.createNewFile(); //--写入vbs内容 String excelPath = dirName+"//"+excelname; writerLine(FileName,"Set objExcel = CreateObject(/"Excel.Application/")"); writerLine(FileName," objExcel.Visible = True "); writerLine(FileName,"Set objWorkbook = objExcel.Workbooks.Open (/""+excelPath+"/")"); //writerLine(FileName,"objExcel.Cells(1,1).Value = /"123/""); writerLine(FileName,"objExcel.Workbooks(1).Save '保存工作表' "); writerLine(FileName,"objExcel.Workbooks(1).Close '关闭工作表' "); writerLine(FileName,"objExcel.Quit '退出' "); //--执行生成的脚本 String[] cpCmd = new String[]{"wscript", FileName}; Process process = Runtime.getRuntime().exec(cpCmd); // wait for the process end int val = process.waitFor();//val 是返回值 } } } catch (Exception e) { e.printStackTrace(); } } public static void writerLine(String path, String contents) { try { FileWriter fileWriter = new FileWriter(path, true); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.write(contents); bufferedWriter.newLine(); bufferedWriter.flush(); bufferedWriter.close(); fileWriter.close(); } catch (IOException ioe) { } } }

你可能感兴趣的:(java,exception,windows,String,Excel,Office)