`
蛤蟆仙人
  • 浏览: 114726 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论
收藏列表
标题 标签 来源
jacob 生成ppt jacob
package cn.com.hongyousoft.pandorax.ppt;

import java.io.File;

import cn.com.hongyousoft.pandorax.CellUtil;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

public class MyTest {
    
    public static final int WORD_HTML = 8;
    
    public static final int WORD_TXT = 7;
    
    public static final int EXCEL_HTML = 44;
    
    public static final int ppSaveAsJPG = 17;
    
    private static final String ADD_CHART = "AddChart";
    
    private ActiveXComponent ppt;
    private ActiveXComponent presentation;
    
    /** 
     * 构造一个新的PPT 
     * @param isVisble 
     */
    public MyTest(boolean isVisble) {
        if (null == ppt) {
            ppt = new ActiveXComponent("PowerPoint.Application");
            //            ppt.setProperty("Visible", new Variant(isVisble));  
            //            ppt.setProperty("WindowState ", new Variant(2));  
            ActiveXComponent presentations = ppt.getPropertyAsComponent("Presentations");
            presentation = presentations.invokeGetComponent("Add", new Variant(1));
        }
    }
    
    public MyTest(String filePath, boolean isVisble) throws Exception {
        if (null == filePath || "".equals(filePath)) {
            throw new Exception("文件路径为空!");
        }
        File file = new File(filePath);
        if (!file.exists()) {
            throw new Exception("文件不存在!");
        }
        ppt = new ActiveXComponent("PowerPoint.Application");
        setIsVisble(ppt, isVisble);
        // 打开一个现有的 Presentation 对象  
        ActiveXComponent presentations = ppt.getPropertyAsComponent("Presentations");
        presentation = presentations.invokeGetComponent("Open", new Variant(filePath), new Variant(true));
    }
    
    public MyTest(String filePath, String tarPath, boolean isVisble) throws Exception {
        if (null == filePath || "".equals(filePath)) {
            throw new Exception("文件路径为空!");
        }
        File file = new File(filePath);
        if (!file.exists()) {
            throw new Exception("文件不存在!");
        }
        ppt = new ActiveXComponent("PowerPoint.Application");
        setIsVisble(ppt, isVisble);
        // 打开一个现有的 Presentation 对象  
        ActiveXComponent presentations = ppt.getPropertyAsComponent("Presentations");
        presentation = presentations.invokeGetComponent("Open", new Variant(filePath), new Variant(true));
    }
    
    /** 
     * 播放ppt 
     *  
     * @param pptFile 
     * @date 2009-7-4 
     * @author YHY 
     */
    public void PPTShow(String pptFile) {
        // powerpoint幻灯展示设置对象  
        ActiveXComponent setting = presentation.getPropertyAsComponent("SlideShowSettings");
        // 调用该对象的run函数实现全屏播放  
        setting.invoke("Run");
        // 释放控制线程  
        ComThread.Release();
    }
    
    /** 
     * ppt另存为 
     *  
     * @param presentation 
     * @param saveTo 
     * @param ppSaveAsFileType 
     * @date 2009-7-4 
     * @author YHY 
     */
    public void saveAs(Dispatch presentation, String saveTo, int ppSaveAsFileType) throws Exception {
        Dispatch.call(presentation, "SaveAs", saveTo, new Variant(ppSaveAsFileType));
    }
    
    /** 
     * 关闭PPT并释放线程 
     * @throws Exception 
     */
    public void closePpt() throws Exception {
        if (null != presentation) {
            Dispatch.call(presentation, "Close");
        }
        ppt.invoke("Quit", new Variant[] {});
        ComThread.Release();
    }
    
    public void closeFile() throws Exception {
        if (null != presentation) {
            Dispatch.call(presentation, "Close");
        }
        ComThread.Release();
    }
    
    /** 
     * 运行PPT 
     * @throws Exception 
     */
    public void runPpt() throws Exception {
        ActiveXComponent setting = presentation.getPropertyAsComponent("SlideShowSettings");
        setting.invoke("Run");
    }
    
    /** 
     * 设置是否可见 
     * @param visble 
     * @param obj 
     */
    private void setIsVisble(Dispatch obj, boolean visble) throws Exception {
        Dispatch.put(obj, "Visible", new Variant(visble));
    }
    
    /** 
     *  
     * @param pageShapes 页面的SHAPES的对象 
     * @param chartType 图表类型 
     * @param leftDistance 距离左边框的距离 
     * @param topDistance 距离上边框的距离 
     * @param width 图表的宽度 
     * @param height 图表的高度 
     * @return 
     * @throws Exception 
     */
    public static Dispatch addChart(Dispatch pageShapes, int chartType, int leftDistance, int topDistance, int width,
            int height) throws Exception {
        Variant chart = Dispatch.invoke(pageShapes, ADD_CHART, 1, new Object[] { new Integer(chartType),//图表类型  
                new Integer(leftDistance),//距离左边框的距离  
                new Integer(topDistance),//距离上边框的距离  
                new Integer(width),//图表的宽度  
                new Integer(height),//图表的高度  
        }, new int[1]);//错误类型  
        
        return chart.toDispatch();
    }
    
    /** 
     * 获取第几个幻灯片 
     * @param index 序号,从1开始 
     * @return 
     * @throws Exception 
     */
    public Dispatch getPptPage(int pageIndex) throws Exception {
        //获取幻灯片对象  
        ActiveXComponent slides = presentation.getPropertyAsComponent("Slides");
        //获得第几个PPT  
        Dispatch pptPage = Dispatch.call(slides, "Item", new Object[] { new Variant(pageIndex) }).toDispatch();
        try {
            Dispatch.call(pptPage, "Select");
        } catch (Exception e) {
            Dispatch.call(pptPage, "Select");
        }
        return pptPage;
    }
    
    /**
     * @Description: 第2页PPT操作
     * @param window
     * @param pageIndex
     * @throws Exception
     */
    private void scyxPPT2(Dispatch window, int pageIndex) throws Exception {
        getPptPage(pageIndex);
        
        //获取当前页中的Shape对象
        Dispatch shapes = getShapes(window);
        
        //获取Shape中的第1个元素  
        int shapeIndex = 1;
        Dispatch shape1 = getShapeByIndex(shapes, shapeIndex);
        
        //第几期赋值
        addText(shape1, "(第20期)");
        
        //获取Shape中的第2个元素  
        shapeIndex = 2;
        Dispatch shape2 = getShapeByIndex(shapes, shapeIndex);
        
        //日期赋值
        addText(shape2, "2012年12月21日");
    }
    
    /**
     * @Description: 第4页PPT操作
     * @param window
     * @param pageIndex
     * @throws Exception
     */
    private void scyxPPT4(Dispatch window, int pageIndex) throws Exception {
        getPptPage(pageIndex);
        
        //获取当前页中的Shape对象
        Dispatch shapes = getShapes(window);
        
        //获取Shape中的第2个元素  
        int shapeIndex = 2;
        Dispatch shape1 = getShapeByIndex(shapes, shapeIndex);
        
        Dispatch.call(shape1, "Select");
        
        //第几期赋值
        addText(shape1, "12月第3周, 原油平均日产0万吨, 比计划低10000万吨");
        //获取幻灯片中的第N个元素 
        shapeIndex = 1;
        Dispatch chartData = getChartData(shapes, shapeIndex);
        
        Dispatch.call(chartData, "Activate");//激活excel sheet,不激活无法修改数据
        
        //获得excel对象
        Dispatch workBook = Dispatch.get(chartData, "Workbook").getDispatch();
        Dispatch workSheetItem = this.getWorkSheetItem(workBook);
        
        int[] plans = { 88888, 59548, 30323, 27516, 15000, 15903, 12774, 11774, 5613, 4484, 4290, 1419, 355, 548, 129 };
        int[] realitys = { 188888, 159548, 130323, 127516, 115000, 115903, 112774, 111774, 15613, 14484, 14290, 11419,
                1355, 1548, 1129 };
        char c = 'B';//定义英语大写首字母
        for (int i = 1; i <= 15; i++) {
            // 修改计划的值
            Dispatch cell = Dispatch.invoke(workSheetItem, "Range", Dispatch.Get, new Object[] { c + "2" }, new int[1])
                    .toDispatch();
            Dispatch.put(cell, "Value", plans[i - 1]);
            
            // 修改实际的值
            cell = Dispatch.invoke(workSheetItem, "Range", Dispatch.Get, new Object[] { c + "3" }, new int[1])
                    .toDispatch();
            Dispatch.put(cell, "Value", realitys[i - 1]);
            c++;
        }
        Dispatch.call(workBook, "Close"); //关闭当前excel文件
    }
    
    /**
     * @Description: 第5页PPT操作
     * @param window
     * @param pageIndex
     * @throws Exception
     */
    private void scyxPPT5(Dispatch window, int pageIndex) throws Exception {
        getPptPage(pageIndex);
        
        //获取当前页中的Shape对象
        Dispatch shapes = getShapes(window);
        
        //获取Shape中的第2个元素  
        int shapeIndex = 2;
        Dispatch shape1 = getShapeByIndex(shapes, shapeIndex);
        Dispatch.call(shape1, "Select");
        //第几期赋值
        addText(shape1, "12月第3周,平均日产2亿方/日, 与月度基本计划一致,主要气区生产平稳");
        //获取幻灯片中的第1个元素  操作图表
        
        shapeIndex = 1;
        Dispatch chartData = getChartData(shapes, shapeIndex);
        
        Dispatch.call(chartData, "Activate");//激活excel sheet,不激活无法修改数据
        
        //获得excel对象
        Dispatch workBook = Dispatch.get(chartData, "Workbook").getDispatch();
        Dispatch workSheetItem = this.getWorkSheetItem(workBook);
        
        String[] companys = { "新疆", "大庆", "股份", "青海", "塔里木" };
        int[] plans = { 8, 5, 3, 4, 6 };
        int[] realitys = { 88, 55, 33, 44, 66 };
        char c = 'B';//定义英语大写首字母
        for (int i = 1; i <= 5; i++) {
            // 修改公司的值
            Dispatch cell = Dispatch.invoke(workSheetItem, "Range", Dispatch.Get, new Object[] { c + "1" }, new int[1])
                    .toDispatch();
            Dispatch.put(cell, "Value", companys[i - 1]);
            // 修改计划的值
            cell = Dispatch.invoke(workSheetItem, "Range", Dispatch.Get, new Object[] { c + "2" }, new int[1])
                    .toDispatch();
            Dispatch.put(cell, "Value", plans[i - 1]);
            
            // 修改实际的值
            cell = Dispatch.invoke(workSheetItem, "Range", Dispatch.Get, new Object[] { c + "3" }, new int[1])
                    .toDispatch();
            Dispatch.put(cell, "Value", realitys[i - 1]);
            c++;
        }
        Dispatch.call(workBook, "Close"); //关闭当前excel文件
    }
    
    /**
     * @Description: 第7页PPT操作
     * @param window
     * @param pageIndex
     * @throws Exception
     */
    private void scyxPPT7(Dispatch window, int pageIndex) throws Exception {
        getPptPage(pageIndex);
        
        //获取当前页中的Shape对象
        Dispatch shapes = getShapes(window);
        
        //获取幻灯片中的第1个元素  操作图表
        
        int shapeIndex = 1;
        Dispatch chartData = getChartData(shapes, shapeIndex);
        
        Dispatch.call(chartData, "Activate");//激活excel sheet,不激活无法修改数据
        
        //获得excel对象
        Dispatch workBook = Dispatch.get(chartData, "Workbook").getDispatch();
        Dispatch workSheetItem = this.getWorkSheetItem(workBook);
        
        String[] companys = { "陕京线", "靖西线 ", "忠武线", " 涩宁兰线", "西气东输" };
        String[] plans = { "1.8", "1.5", "1.3", "1.4", "1.6" };
        String[] realitys = { "1.8", "2.5", "2.3", "2.4", "2.6" };
        char c = 'B';//定义英语大写首字母
        for (int i = 1; i <= 5; i++) {
            // 修改管线的值
            Dispatch cell = Dispatch.invoke(workSheetItem, "Range", Dispatch.Get, new Object[] { c + "1" }, new int[1])
                    .toDispatch();
            Dispatch.put(cell, "Value", companys[i - 1]);
            // 修改计划的值
            cell = Dispatch.invoke(workSheetItem, "Range", Dispatch.Get, new Object[] { c + "2" }, new int[1])
                    .toDispatch();
            Dispatch.put(cell, "Value", plans[i - 1]);
            
            // 修改实际的值
            cell = Dispatch.invoke(workSheetItem, "Range", Dispatch.Get, new Object[] { c + "3" }, new int[1])
                    .toDispatch();
            Dispatch.put(cell, "Value", realitys[i - 1]);
            c++;
        }
        Dispatch.call(workBook, "Close"); //关闭当前excel文件
    }
    
    /**
     * @Description: 第9页PPT操作
     * @param window
     * @param pageIndex
     * @throws Exception
     */
    private void scyxPPT9(Dispatch window, int pageIndex) throws Exception {
        getPptPage(pageIndex);
        
        //获取当前页中的Shape对象
        Dispatch shapes = getShapes(window);
        
        //获取Shape中的第2个元素  
        int shapeIndex = 3;
        Dispatch shape1 = getShapeByIndex(shapes, shapeIndex);
        Dispatch.call(shape1, "Select");
        //第几期赋值
        addText(shape1, "\r\t本周动用钻机2000台, 比上周增加100台." + "\r\n" + "平均日钻井进尺20万米,其中开发井20.18万米,探井及评价井5万米");
        
        //获取幻灯片中的第1个元素  操作饼状图表
        
        shapeIndex = 1;
        Dispatch chartData = getChartData(shapes, shapeIndex);
        
        Dispatch.call(chartData, "Activate");//激活excel sheet,不激活无法修改数据
        
        //获得excel对象
        Dispatch workBook = Dispatch.get(chartData, "Workbook").getDispatch();
        Dispatch workSheetItem = this.getWorkSheetItem(workBook);
        
        // 修改开发井的值
        Dispatch cell = Dispatch.invoke(workSheetItem, "Range", Dispatch.Get, new Object[] { "B2" }, new int[1])
                .toDispatch();
        Dispatch.put(cell, "Value", "5000");
        // 修改勘探井的值
        cell = Dispatch.invoke(workSheetItem, "Range", Dispatch.Get, new Object[] { "C2" }, new int[1]).toDispatch();
        Dispatch.put(cell, "Value", "500");
        
        //获取幻灯片中的第2个元素  操作图表
        
        shapeIndex = 2;
        chartData = getChartData(shapes, shapeIndex);
        
        Dispatch.call(chartData, "Activate");//激活excel sheet,不激活无法修改数据
        
        //获得excel对象
        workSheetItem = this.getWorkSheetItem(workBook);
        // 修改总进尺的值
        cell = Dispatch.invoke(workSheetItem, "Range", Dispatch.Get, new Object[] { "B2" }, new int[1]).toDispatch();
        Dispatch.put(cell, "Value", "18.88");
        // 修改开发井的值
        cell = Dispatch.invoke(workSheetItem, "Range", Dispatch.Get, new Object[] { "C2" }, new int[1]).toDispatch();
        Dispatch.put(cell, "Value", "16.66");
        // 修改勘探井的值
        cell = Dispatch.invoke(workSheetItem, "Range", Dispatch.Get, new Object[] { "D2" }, new int[1]).toDispatch();
        Dispatch.put(cell, "Value", "8.88");
        Dispatch.call(workBook, "Close"); //关闭当前excel文件
    }
    
    /**
     * @Description: 第10页PPT操作
     * @param window
     * @param pageIndex
     * @throws Exception
     */
    private void scyxPPT10(Dispatch window, int pageIndex) throws Exception {
        getPptPage(pageIndex);
        
        //获取当前页中的Shape对象
        Dispatch shapes = getShapes(window);
        
        //获取幻灯片中的第1个元素  操作饼状图表
        
        int shapeIndex = 1;
        Dispatch chartData = getChartData(shapes, shapeIndex);
        
        Dispatch.call(chartData, "Activate");//激活excel sheet,不激活无法修改数据
        
        //获得excel对象
        Dispatch workBook = Dispatch.get(chartData, "Workbook").getDispatch();
        Dispatch workSheetItem = this.getWorkSheetItem(workBook);
        
        for (int i = 2; i < 7; i++) {
            String s = "a";
            for (int j = 0; j < 52; j++) {
                s = CellUtil.getCellIndex(s);
                // 修改曲线图的值
                Dispatch cell = Dispatch.invoke(workSheetItem, "Range", Dispatch.Get, new Object[] { s + "" + i },
                        new int[1]).toDispatch();
                Dispatch.put(cell, "Value", (int) (Math.random() * 1000));
                s = s.toLowerCase();
            }
        }
        Dispatch.call(workBook, "Close"); //关闭当前excel文件
    }
    
    /**
     * @Description: 第11页PPT操作
     * @param window
     * @param pageIndex
     * @throws Exception
     */
    private void scyxPPT11(Dispatch window, int pageIndex) throws Exception {
        getPptPage(pageIndex);
        
        //获取当前页中的Shape对象
        Dispatch shapes = getShapes(window);
        //获取Shape中的第2个元素  
        int shapeIndex = 2;
        Dispatch shape1 = getShapeByIndex(shapes, shapeIndex);
        Dispatch.call(shape1, "Select");
        //第几期赋值
        addText(shape1, "新疆油田");
        //获取幻灯片中的第1个元素  操作饼状图表
        
        shapeIndex = 1;
        Dispatch chartData = getChartData(shapes, shapeIndex);
        
        Dispatch.call(chartData, "Activate");//激活excel sheet,不激活无法修改数据
        
        //获得excel对象
        Dispatch workBook = Dispatch.get(chartData, "Workbook").getDispatch();
        Dispatch workSheetItem = this.getWorkSheetItem(workBook);
        
        for (int i = 2; i < 5; i++) {
            String s = "a";
            for (int j = 0; j < 52; j++) {
                s = CellUtil.getCellIndex(s);
                // 修改曲线图的值
                Dispatch cell = Dispatch.invoke(workSheetItem, "Range", Dispatch.Get, new Object[] { s + "" + i },
                        new int[1]).toDispatch();
                Dispatch.put(cell, "Value", (int) (Math.random() * 1000));
                s = s.toLowerCase();
            }
        }
        Dispatch.call(workBook, "Close"); //关闭当前excel文件
    }
    
    /**
     * @Description: 第12页PPT操作
     * @param window
     * @param pageIndex
     * @throws Exception
     */
    private void scyxPPT12(Dispatch window, int pageIndex) throws Exception {
        getPptPage(pageIndex);
        
        //获取当前页中的Shape对象
        Dispatch shapes = getShapes(window);
        //获取Shape中的第2个元素  
        int shapeIndex = 2;
        Dispatch shape1 = getShapeByIndex(shapes, shapeIndex);
        Dispatch.call(shape1, "Select");
        //第几期赋值
        addText(shape1, "大庆油田");
        //获取幻灯片中的第1个元素  操作饼状图表
        
        shapeIndex = 1;
        Dispatch chartData = getChartData(shapes, shapeIndex);
        
        Dispatch.call(chartData, "Activate");//激活excel sheet,不激活无法修改数据
        
        //获得excel对象
        Dispatch workBook = Dispatch.get(chartData, "Workbook").getDispatch();
        Dispatch workSheetItem = this.getWorkSheetItem(workBook);
        
        for (int i = 2; i < 5; i++) {
            String s = "a";
            for (int j = 0; j < 52; j++) {
                s = CellUtil.getCellIndex(s);
                // 修改曲线图的值
                Dispatch cell = Dispatch.invoke(workSheetItem, "Range", Dispatch.Get, new Object[] { s + "" + i },
                        new int[1]).toDispatch();
                Dispatch.put(cell, "Value", (int) (Math.random() * 160));
                s = s.toLowerCase();
            }
        }
        Dispatch.call(workBook, "Close"); //关闭当前excel文件
    }
    
    /**
     * @Description: 第13页PPT操作
     * @param window
     * @param pageIndex
     * @throws Exception
     */
    private void scyxPPT13(Dispatch window, int pageIndex) throws Exception {
        getPptPage(pageIndex);
        
        //获取当前页中的Shape对象
        Dispatch shapes = getShapes(window);
        //获取Shape中的第2个元素  
        int shapeIndex = 2;
        Dispatch shape1 = getShapeByIndex(shapes, shapeIndex);
        Dispatch.call(shape1, "Select");
        //第几期赋值
        addText(shape1, "辽河油田");
        //获取幻灯片中的第1个元素  操作饼状图表
        
        shapeIndex = 1;
        Dispatch chartData = getChartData(shapes, shapeIndex);
        
        Dispatch.call(chartData, "Activate");//激活excel sheet,不激活无法修改数据
        
        //获得excel对象
        Dispatch workBook = Dispatch.get(chartData, "Workbook").getDispatch();
        Dispatch workSheetItem = this.getWorkSheetItem(workBook);
        
        for (int i = 2; i < 5; i++) {
            String s = "a";
            for (int j = 0; j < 52; j++) {
                s = CellUtil.getCellIndex(s);
                // 修改曲线图的值
                Dispatch cell = Dispatch.invoke(workSheetItem, "Range", Dispatch.Get, new Object[] { s + "" + i },
                        new int[1]).toDispatch();
                Dispatch.put(cell, "Value", (int) (Math.random() * 140));
                s = s.toLowerCase();
            }
        }
        Dispatch.call(workBook, "Close"); //关闭当前excel文件
    }
    
    /**
     * @Description: 第14页PPT操作
     * @param window
     * @param pageIndex
     * @throws Exception
     */
    private void scyxPPT14(Dispatch window, int pageIndex) throws Exception {
        getPptPage(pageIndex);
        
        //获取当前页中的Shape对象
        Dispatch shapes = getShapes(window);
        int shapeIndex = 2;
        Dispatch shape1 = getShapeByIndex(shapes, shapeIndex);
        Dispatch.call(shape1, "Select");
        //第几期赋值
        addText(shape1, "华北油田");
        //获取幻灯片中的第1个元素  操作饼状图表
        
        shapeIndex = 1;
        Dispatch chartData = getChartData(shapes, shapeIndex);
        
        Dispatch.call(chartData, "Activate");//激活excel sheet,不激活无法修改数据
        //获得excel对象
        Dispatch workBook = Dispatch.get(chartData, "Workbook").getDispatch();
        Dispatch workSheetItem = this.getWorkSheetItem(workBook);
        
        for (int i = 2; i < 5; i++) {
            String s = "a";
            for (int j = 0; j < 52; j++) {
                s = CellUtil.getCellIndex(s);
                // 修改曲线图的值
                Dispatch cell = Dispatch.invoke(workSheetItem, "Range", Dispatch.Get, new Object[] { s + "" + i },
                        new int[1]).toDispatch();
                Dispatch.put(cell, "Value", (int) (Math.random() * 120));
                s = s.toLowerCase();
            }
        }
        Dispatch.call(workBook, "Close"); //关闭当前excel文件
    }
    
    public Dispatch getWorkSheetItem(Dispatch workBook) {
        
        Dispatch workSheets = Dispatch.get(workBook, "Worksheets").getDispatch();
        return Dispatch.call(workSheets, "Item", new Variant(1)).toDispatch();
    }
    
    /**
     * @Description: 获得操作表的对象
     * @param shapes
     * @param shapeIndex
     * @return
     */
    private Dispatch getChartData(Dispatch shapes, int shapeIndex) {
        Dispatch shape = Dispatch.call(shapes, "Item", new Variant(shapeIndex)).toDispatch();
        Dispatch.call(shape, "Select");
        Dispatch chart = Dispatch.get(shape, "Chart").getDispatch();
        Dispatch chartData = Dispatch.get(chart, "ChartData").getDispatch();
        return chartData;
    }
    
    /** 
     * 设置图表上是否显示数据表格 
     * @param chartObj 
     * @param value 
     * @throws Exception 
     */
    public static void setHasDataTable(Dispatch chartObj, boolean value) throws Exception {
        Dispatch.put(chartObj, "HasDataTable", value);
    }
    
    /**
     * @Description: 文本域赋值
     * @param shape
     */
    private void addText(Dispatch shape, String value) {
        Dispatch textFrame = Dispatch.get(shape, "TextFrame").getDispatch();
        Dispatch textRange = Dispatch.get(textFrame, "TextRange").getDispatch();
        Dispatch.call(textRange, "Select");
        Dispatch.put(textRange, "Text", value);
    }
    
    /**
     * @Description: 获取Shape中的第几个元素  
     * @param shapes
     * @param shapeIndex
     * @return
     */
    private Dispatch getShapeByIndex(Dispatch shapes, int shapeIndex) {
        Dispatch shape = Dispatch.call(shapes, "Item", new Variant(shapeIndex)).toDispatch();
        try {
            Dispatch.call(shape, "Select");
        } catch (Exception e) {
            Dispatch.call(shape, "Select");
        }
        return shape;
    }
    
    /**
     * @Description: 获取当前页中的Shape对象
     * @param window
     * @return
     */
    private Dispatch getShapes(Dispatch window) {
        Dispatch selection = Dispatch.get(window, "Selection").toDispatch();
        Dispatch slideRange = Dispatch.get(selection, "SlideRange").getDispatch();
        Dispatch shapes = Dispatch.get(slideRange, "Shapes").getDispatch();
        return shapes;
    }
    
    public static void main(String[] strs) throws Exception {
        String templatePPT = "e:/生成运行周报模版1.pptx";
        
        MyTest test = new MyTest(templatePPT, true);
        test.generageSCYXZBPpt();
    }
    
    /**
     * @Description: 生成PPT
     * @throws Exception
     */
    public void generageSCYXZBPpt() throws Exception {
        long startTime = System.currentTimeMillis();
        Dispatch windows = presentation.getProperty("Windows").toDispatch();
        
        //获取打开的第几个ppt文件
        int pptFileIndex = 1; //第几个ppt文件,一个powerpoint可能同时打开多个文件。此处应注意唯一性,存在并发问题,可考虑先拷贝模板为其他文件,然后打开,并赋值。
        Dispatch window = Dispatch.call(windows, "Item", new Variant(pptFileIndex)).toDispatch();
        
        //操作PPT中第2页
        int pageIndex = 2;
        scyxPPT2(window, pageIndex);
        
        //操作PPT中第4页
        pageIndex = 4;
        scyxPPT4(window, pageIndex);
        
        //操作PPT中第5页
        pageIndex = 5;
        scyxPPT5(window, pageIndex);
        
        //操作PPT中第7页
        pageIndex = 7;
        scyxPPT7(window, pageIndex);
        
        //操作PPT中第9页
        pageIndex = 9;
        scyxPPT9(window, pageIndex);
        
        //操作PPT中第10页
        pageIndex = 10;
        scyxPPT10(window, pageIndex);
        
        //操作PPT中第11页
        pageIndex = 11;
        scyxPPT11(window, pageIndex);
        //操作PPT中第12页
        pageIndex = 12;
        scyxPPT12(window, pageIndex);
        //操作PPT中第13页
        pageIndex = 13;
        scyxPPT13(window, pageIndex);
        //操作PPT中第14页
        pageIndex = 14;
        scyxPPT14(window, pageIndex);
        
        //保存ppt
        presentation.invoke("SaveAs", new Variant("e:/测试.pptx"));
        //        PPTShow("e:/测试.pptx");
        //关闭当前ppt文件
        if (null != presentation) {
            Dispatch.call(presentation, "Close");
        }
        //      
        //退出powerpoint
        ppt.invoke("Quit", new Variant[] {});
        // 释放控制线程
        ComThread.Release();
        long endTime = System.currentTimeMillis();
        System.out.println("====" + (endTime - startTime));
    }
}
文件删除客户端 文件删除
package cn.com.hongyousoft.pandorax.fileclient.client;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpDropFile {
    public static void main(String[] args) throws MalformedURLException, IOException {
        URL url = new URL("http://10.71.197.240:9082/file/dropfile");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(true);
        con.setDefaultUseCaches(false);
        con.setConnectTimeout(30000);
        con.setReadTimeout(30000);
        con.setRequestMethod("GET");
        //以下是设置头信息参数
        con.setRequestProperty("transfer-file-name", "三维地图测试.zip");//要删除的文件名
        con.setRequestProperty("business-id", "10001");//业务ID
        con.setRequestProperty("area-code", "zb");//公司代码
        con.setRequestProperty("fileKey", "fileKey");//操作权限标识
        con.setRequestProperty("business_year", "2012");//业务创建的年份
        con.setRequestProperty("business_month", "5");//业务创建的月份
        
        /*
         * 这里是从服务端获取操作的结果
         * 成功时 信息将为:success
         * 错误时 信息为类似这样的错误提示信息:{"errorCode":20001,"errorMessage":文件不存在}
         */
        String msg = con.getHeaderField("result");
        System.out.println(msg);
    }
}
文件下载客户端 文件下载
package cn.com.hongyousoft.pandorax.fileclient.client;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpDownFile {
    
    /**
     * @Description: 文件下载
     * @param url
     * @return
     */
    public static void main(String[] args) {
        
        // 首先 判断本地是否存在要下载的文件  如果存在 得到其已下载的大小 这里省略
        
        long nPos = 0L; //得到已下载文件的的大小  当不存在时  为0
        RandomAccessFile out = null;
        BufferedInputStream in = null;
        HttpURLConnection con = null;
        try {
            URL url = new URL("http://10.71.197.238/file/downloadfile");
            con = (HttpURLConnection) url.openConnection();
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(true);
            con.setDefaultUseCaches(false);
            con.setConnectTimeout(30000);
            con.setReadTimeout(30000);
            con.setRequestMethod("GET");
            
            //以下是设置头信息参数
            con.setRequestProperty("transfer-file-name", "三维地图测试.zip");//要删除的文件名
            con.setRequestProperty("business-id", "10001");//业务ID
            con.setRequestProperty("area-code", "zb");//公司代码
            con.setRequestProperty("fileKey", "fileKey");//操作权限标识
            con.setRequestProperty("business_year", "2012");//业务创建的年份
            con.setRequestProperty("business_month", "5");//业务创建的月份
            
            // 设置User-Agent
            con.setRequestProperty("User-Agent", "Net");
            
            // 设置续传开始 此处参数的值  格式如 "bytes=100-" 表示从100字节开始续传
            con.setRequestProperty("Range", "bytes=" + nPos + "-");
            
            // 获取输入流
            in = new BufferedInputStream(con.getInputStream());
            
            out = new RandomAccessFile("e://下载测试.zip", "rw");
            int size = 0;
            byte[] buf = new byte[10240];
            
            out.seek(nPos);
            while ((size = in.read(buf)) != -1) {
                out.write(buf, 0, size);
            }
            /*
             * 这里是从服务端获取操作的结果
             * 错误时 信息为类似这样的错误提示信息:{"errorCode":20001,"errorMessage":文件不存在}
             */
            String msg = con.getHeaderField("result");
            System.out.println(msg);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null)
                    in.close();
                if (out != null)
                    out.close();
                if (con != null)
                    con.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    /**
     * @Description: 获得要下载文件的大小
     * @param url
     * @return
     */
    public static void main1(String[] args) {
        try {
            URL url = new URL("http://10.71.197.238/file/filesize");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(true);
            con.setDefaultUseCaches(false);
            con.setConnectTimeout(30000);
            con.setReadTimeout(30000);
            con.setRequestMethod("GET");
            
            //以下是设置头信息参数
            con.setRequestProperty("transfer-file-name", "三维地图测试.zip");//要获得文件大小的文件名
            con.setRequestProperty("business-id", "10001");//业务ID
            con.setRequestProperty("area-code", "zb");//公司代码
            con.setRequestProperty("fileKey", "fileKey");//操作权限标识
            con.setRequestProperty("business_year", "2012");//业务创建的年份
            con.setRequestProperty("business_month", "5");//业务创建的月份
            
            /*
             * 这里是从服务端获取操作的结果
             * 当文件存在时:文件大小
             * 当文件不存在时:返回-1
             * 错误时:类似这样的提示信息:{"errorCode":20001,"errorMessage":文件不存在}
             */
            String msg = con.getHeaderField("result");
            System.out.println(msg);
            
            con.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
文件上传客户端 文件上传
package cn.com.hongyousoft.pandorax.fileclient.client;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpSendFile {
    public static final int BUFFER_SIZE = 4096;
    
    public static final long MAX_FILE_SIZE = 1024 * 1024 * 300; //300M. allowed the max size of file
    
    public static void main(String[] args) throws Exception {
        File file = new File("e://三维地图测试.zip");
        long fileSize = file.length();
        if (fileSize > MAX_FILE_SIZE) {
            System.out.println("文件上传不能超过300M");
        }
        OutputStream out = null;
        
        FileInputStream translatedFile = null;
        try {
            //获取需要续传的文件位置
            long lastPositon = getLastedPosition();
            
            translatedFile = new FileInputStream(file);
            if (lastPositon > 0)
                translatedFile.skip(lastPositon);
            
            URL url = new URL("http://10.71.197.241/file/uploadfile");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(true);
            con.setDefaultUseCaches(false);
            con.setConnectTimeout(30000);
            con.setReadTimeout(30000);
            
            con.setRequestMethod("POST");
            
            //以下是设置头信息参数
            con.setRequestProperty("transfer-file-name", "三维地图测试.zip");//要获得文件大小的文件名
            con.setRequestProperty("business-id", "10001");//业务ID
            con.setRequestProperty("area-code", "zb");//公司代码
            con.setRequestProperty("fileKey", "fileKey");//操作权限标识
            con.setRequestProperty("business_year", "2012");//业务创建的年份
            con.setRequestProperty("business_month", "5");//业务创建的月份
            con.setRequestProperty("Charset", "UTF-8");
            con.setRequestProperty("Transfer-Encoding", "chunked");
            con.setChunkedStreamingMode(4096);
            
            out = con.getOutputStream();
            int readSize = 0;
            byte[] buf = new byte[BUFFER_SIZE];
            while ((readSize = translatedFile.read(buf)) != -1) {
                out.write(buf, 0, readSize);
            }
            out.flush();
            
            String msg = con.getHeaderField("result");
            System.out.println(msg);
            
            con.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null)
                out.close();
            if (translatedFile != null)
                translatedFile.close();
        }
    }
    
    /**
     * @Description: 获得上传过的最后索引位置
     * @return Long
     * @throws IOException
     */
    private static long getLastedPosition() throws IOException {
        long lastPositon = 0;
        URL url = new URL("http://10.71.197.241/file/lastpostion");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(true);
        con.setDefaultUseCaches(false);
        con.setConnectTimeout(30000);
        con.setReadTimeout(30000);
        con.setRequestMethod("GET");
        
        //以下是设置头信息参数
        con.setRequestProperty("transfer-file-name", "三维地图测试.zip");//要获得文件大小的文件名
        con.setRequestProperty("business-id", "10001");//业务ID
        con.setRequestProperty("area-code", "zb");//公司代码
        con.setRequestProperty("fileKey", "fileKey");//操作权限标识
        con.setRequestProperty("business_year", "2012");//业务创建的年份
        con.setRequestProperty("business_month", "5");//业务创建的月份
        
        /*
         * 这里是从服务端获取操作的结果
         * 当文件存在时:文件大小
         * 当文件不存在时:返回-1
         * 错误时:类似这样的提示信息:{"errorCode":20001,"errorMessage":文件不存在}
         */
        
        lastPositon = Long.valueOf(con.getHeaderField("result"));
        System.out.println("文件长度" + lastPositon);
        return lastPositon;
    }
    
}
文件删除服务 文件删除
package cn.com.hongyousoft.pandorax.fileservice.service;

import java.io.File;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.com.hongyousoft.pandorax.fileservice.common.BaseService;
import cn.com.hongyousoft.pandorax.fileservice.util.FileUtil;
import cn.com.hongyousoft.pandorax.fileservice.util.ParamConstant;

/**
 * @ClassName: HttpDropService
 * @Description: 删除文件的服务
 */
@SuppressWarnings("serial")
@Controller
public class HttpDropService extends BaseService {
    /**
     * @Description: 文件删除的service方法
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping(value = "/dropfile", method = RequestMethod.GET)
    public void dropService(HttpServletRequest request, HttpServletResponse response) {
        try {
            String filePathName = generateFilePathName(request, response);
            if (null == filePathName) {
                response.setHeader(ParamConstant.RESULT, getErrorResult(ParamConstant.ERROR_PARAMERROR_FILENAME));
                return;
            }
            if (StringUtils.isEmpty(filePathName)) {
                response.setHeader(ParamConstant.RESULT, getErrorResult(ParamConstant.ERROR_PARAMERROR));
                return;
            }
            File destFile = new File(filePathName);
            if (destFile.exists()) {
                boolean flag = destFile.delete();
                if (flag) {
                    response.setHeader(ParamConstant.RESULT, ParamConstant.FILE_MESSAGE_SUCCESS);
                } else {
                    response.setHeader(ParamConstant.RESULT, getErrorResult(ParamConstant.ERROR_FILE_OPERATION));
                }
            } else {
                response.setHeader(ParamConstant.RESULT, getErrorResult(ParamConstant.ERROR_FILE_EXIST_FALSE));
            }
        } catch (Exception e) {
            response.setHeader(ParamConstant.RESULT, getErrorResult(ParamConstant.ERROR_SYSTEM));
            LOG.error(e.getMessage(), e);
        }
    }
    
    /**
     * @Description: 生成上传和下载文件的路径+文件名
     * @param request
     * @param response
     * @return
     * @throws UnsupportedEncodingException
     */
    private String generateFilePathName(HttpServletRequest request, HttpServletResponse response)
            throws UnsupportedEncodingException {
        String fileKey = "";
        String filePath = FileUtil.generateFilePath(request, response);
        if (StringUtils.isNotEmpty(filePath)) {
            String fileName = "";
            if (null != request.getHeader(ParamConstant.FILE_NAME_HEADER)) {
                fileName = new String(request.getHeader(ParamConstant.FILE_NAME_HEADER).getBytes(), "utf-8");
            }
            fileName = new String(fileName.getBytes("ISO8859-1"), "utf-8");
            //判断文件名是否为空
            if (null == fileName || "".equals(fileName)) {
                return null;
            }
            //路径和文件名
            fileKey = filePath + File.separator + fileName;
        }
        return fileKey;
    }
}
文件下载服务 文件下载
package cn.com.hongyousoft.pandorax.fileservice.service;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.com.hongyousoft.pandorax.fileservice.common.BaseService;
import cn.com.hongyousoft.pandorax.fileservice.util.CommonUtil;
import cn.com.hongyousoft.pandorax.fileservice.util.FileUtil;
import cn.com.hongyousoft.pandorax.fileservice.util.ParamConstant;

/**
 * @ClassName: HttpDownloadService
 * @Description: 下载文件的服务
 */
@SuppressWarnings("serial")
@Controller
public class HttpDownloadService extends BaseService {
    /**
     * @Description: 获得服务器上要下载的文件大小
     * @param req
     * @param resp
     * @param fileName
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping(value = "/filesize", method = RequestMethod.GET)
    public void getFileLength(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        try {
            //获得要下载文件的路径+文件名
            String filePathName = generateFilePathName(request, response);
            if (null == filePathName) {
                response.setHeader(ParamConstant.RESULT, getErrorResult(ParamConstant.ERROR_PARAMERROR_FILENAME));
                return;
            }
            if (StringUtils.isEmpty(filePathName)) {
                response.setHeader(ParamConstant.RESULT, getErrorResult(ParamConstant.ERROR_PARAMERROR));
                return;
            }
            File destFile = new File(filePathName);
            if (destFile.exists()) {
                response.setHeader(ParamConstant.RESULT, String.valueOf(destFile.length()));
            } else {
                response.setHeader(ParamConstant.RESULT, "-1");
            }
        } catch (Exception e) {
            response.setHeader(ParamConstant.RESULT, getErrorResult(ParamConstant.ERROR_SYSTEM));
            LOG.error(e.getMessage(), e);
        }
    }
    
    /**
     * @Description: 下载文件service
     * @param request
     * @param response
     * @throws ServletException
     */
    @RequestMapping(value = "/downloadfile", method = RequestMethod.GET)
    public void downLoadService(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        try {
            //获得要下载文件的路径+文件名
            String filePathName = generateFilePathName(request, response);
            if (null == filePathName) {
                response.setHeader(ParamConstant.RESULT, getErrorResult(ParamConstant.ERROR_PARAMERROR_FILENAME));
                return;
            }
            if (StringUtils.isEmpty(filePathName)) {
                response.setHeader(ParamConstant.RESULT, getErrorResult(ParamConstant.ERROR_PARAMERROR));
                return;
            }
            File file = new File(filePathName);
            if (!file.exists()) {
                response.setHeader(ParamConstant.RESULT, getErrorResult(ParamConstant.ERROR_FILE_EXIST_FALSE));
            } else {
                
                long fileLength = file.length(); //要下载的文件总大小
                long pastLength = 0; //记录已下载文件大小  
                long contentLength = fileLength; //客户端请求的字节总量,  默认全部下载
                
                if (request.getHeader("Range") != null) {// 客户端请求的下载的文件块的开始字节  
                    response.setStatus(javax.servlet.http.HttpServletResponse.SC_PARTIAL_CONTENT);
                    String rangeBytes = request.getHeader("Range").replaceAll("bytes=", "").replaceAll(" ", "");
                    String[] range = rangeBytes.split("-");
                    pastLength = Long.parseLong(range[0]);
                    long toLength = fileLength;// 如bytes=969998336-
                    
                    if (range.length > 1 && !("".equals(range[1]))) {
                        toLength = Long.parseLong(range[1]);
                    }
                    contentLength = toLength - pastLength;
                }
                /** 
                 * 如果设设置了Content-Length,则客户端会自动进行多线程下载。如果不希望支持多线程,则不要设置这个参数。 
                 * 响应的格式是: 
                 * Content-Length: [文件的总大小] - [客户端请求的下载的文件块的开始字节] 
                 * ServletActionContext.getResponse().setHeader("Content-Length", 
                 * new Long(file.length() - p).toString()); 
                 */
                // 通知客户端支持断点续传
                response.reset();
                //如果是第一次下,还没有断点续传,状态是默认的 200,无需显式设置;响应的格式是:HTTP/1.1 200 OK  
                response.setHeader("Accept-Ranges", "bytes");
                
                //如果本地下载过文件  续传
                if (pastLength != 0) {
                    checkBreakPoint(response, fileLength, pastLength);
                }
                //开始下载
                fileDownLoad(response, file, pastLength, contentLength);
            }
        } catch (Exception e) {
            response.setHeader(ParamConstant.RESULT, getErrorResult(ParamConstant.ERROR_SYSTEM));
            LOG.error(e.getMessage(), e);
        }
    }
    
    /**
     * @Description: 生成上传和下载文件的路径+文件名
     * @param request
     * @param response
     * @return
     * @throws UnsupportedEncodingException
     */
    private String generateFilePathName(HttpServletRequest request, HttpServletResponse response)
            throws UnsupportedEncodingException {
        String fileKey = "";
        String filePath = FileUtil.generateFilePath(request, response);
        if (StringUtils.isNotEmpty(filePath)) {
            String fileName = "";
            if (null != request.getHeader(ParamConstant.FILE_NAME_HEADER)) {
                fileName = new String(request.getHeader(ParamConstant.FILE_NAME_HEADER).getBytes(), "utf-8");
            }
            fileName = new String(fileName.getBytes("ISO8859-1"), "utf-8");
            //判断文件名是否为空
            if (null == fileName || "".equals(fileName)) {
                return null;
            }
            //路径和文件名
            fileKey = filePath + File.separator + fileName;
        }
        return fileKey;
    }
    
    /**
     * @Description: 文件下载
     * @param response
     * @param file
     * @param pastLength
     * @param contentLength
     */
    private void fileDownLoad(HttpServletResponse response, File file, long pastLength, long contentLength) {
        RandomAccessFile in = null;
        BufferedOutputStream out = null;
        try {
            response.addHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
            response.addHeader("Content-Length", String.valueOf(contentLength));
            response.setContentType(CommonUtil.setContentType(file.getName()));// set the MIME type.  
            
            out = new BufferedOutputStream(response.getOutputStream());
            in = new RandomAccessFile(file, "r");
            
            in.seek(pastLength);
            
            byte[] buf = new byte[ParamConstant.DOWN_BUFFER_SIZE];
            int read = 0;
            while ((read = in.read(buf)) != -1) {
                out.write(buf, 0, read);
            }
            out.flush();
        } catch (Exception e) {
            response.setHeader(ParamConstant.RESULT, getErrorResult(ParamConstant.ERROR_SYSTEM));
            LOG.error(e.getMessage(), e);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    /**
     * @Description: 设置断点续传下载
     * @param response
     * @param fileLength
     * @param pastLength
     */
    private void checkBreakPoint(HttpServletResponse response, long fileLength, long pastLength) {
        StringBuffer contentRange = new StringBuffer();
        contentRange.append("bytes ");
        contentRange.append(String.valueOf(pastLength));
        contentRange.append("-");
        contentRange.append(String.valueOf(fileLength - 1));
        contentRange.append("/");
        contentRange.append(String.valueOf(fileLength));
        //Content-Range: bytes [文件块的开始字节]-[文件的总大小 - 1]/[文件的总大小]  
        response.setHeader("Content-Range", contentRange.toString());
    }
    
}
文件上传服务 文件上传
package cn.com.hongyousoft.pandorax.fileservice.service;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.com.hongyousoft.pandorax.fileservice.common.BaseService;
import cn.com.hongyousoft.pandorax.fileservice.util.FileUtil;
import cn.com.hongyousoft.pandorax.fileservice.util.ParamConstant;

/**
 * @ClassName: HttpUploadService
 * @Description: 上传文件的服务
 */
@SuppressWarnings("serial")
@Controller
public class HttpUploadService extends BaseService {
    
    /**
     * @Description: 上传和续传文件
     * @param request
     * @param response
     * @param fileName
     * @throws ServletException
     */
    @RequestMapping(value = "/uploadfile", method = RequestMethod.POST)
    public void uploadService(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        String filePath = FileUtil.generateFilePath(request, response);
        String filePathName = getFilePathName(request, response);
        File foldFile = new File(filePath);
        if (!foldFile.exists()) {
            boolean flag = foldFile.mkdirs();
            if (!flag) {
                response.setHeader(ParamConstant.RESULT, getErrorResult(ParamConstant.ERROR_FILE_OPERATION));
                return;
            }
        }
        RandomAccessFile file = null;
        
        file = new RandomAccessFile(new File(filePathName + ".a8"), "rw");
        
        long writePos = 0;
        InputStream in = null;
        try {
            if (null != file) {
                writePos = file.length();
                file.seek(writePos);
            }
            in = request.getInputStream();
            byte[] buf = new byte[ParamConstant.BUFFER_SIZE];
            
            int read = 0;
            while ((read = in.read(buf)) != -1) {
                file.write(buf, 0, read);
            }
            file.close();
            File tmpFile = new File(filePathName + ".a8");
            File destFile = new File(filePathName);
            if (destFile.exists()) {
                boolean flag = destFile.delete();
                if (!flag) {
                    response.setHeader(ParamConstant.RESULT, getErrorResult(ParamConstant.ERROR_FILE_OPERATION));
                    return;
                }
            }
            boolean flag = tmpFile.renameTo(destFile);
            if (!flag) {
                response.setHeader(ParamConstant.RESULT, getErrorResult(ParamConstant.ERROR_FILE_OPERATION));
                return;
            }
            response.setHeader(ParamConstant.RESULT, ParamConstant.FILE_MESSAGE_SUCCESS);
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        } finally {
            try {
                if (null != in) {
                    in.close();
                }
                if (null != file) {
                    file.close();
                }
            } catch (IOException e) {
                LOG.error(e.getMessage(), e);
            }
        }
        
    }
    
    /**
     * @Description: 获取临时文件长度
     * @param resp
     * @param fileName
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping(value = "/lastpostion", method = RequestMethod.GET)
    public void getLastPostFileLength(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String filePathName;
        try {
            filePathName = getFilePathName(request, response);
            
            if (null == filePathName) {
                response.setHeader(ParamConstant.RESULT, getErrorResult(ParamConstant.ERROR_PARAMERROR_FILENAME));
                return;
            }
            if (StringUtils.isEmpty(filePathName)) {
                response.setHeader(ParamConstant.RESULT, getErrorResult(ParamConstant.ERROR_PARAMERROR));
                return;
            }
            File tempFile = new File(filePathName + ".a8");
            if (tempFile.exists()) {
                response.setHeader(ParamConstant.RESULT, String.valueOf(tempFile.length()));
            } else {
                response.setHeader(ParamConstant.RESULT, "-1");
            }
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
            response.setHeader(ParamConstant.RESULT, getErrorResult(ParamConstant.ERROR_SYSTEM));
        }
    }
    
    /**
     * @Description: 获得文件路径和文件名
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    private static String getFilePathName(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String fileKey = "";
        String filePath = FileUtil.generateFilePath(request, response);
        if (StringUtils.isNotEmpty(filePath)) {
            String fileName = "";
            if (null != request.getHeader(ParamConstant.FILE_NAME_HEADER)) {
                fileName = new String(request.getHeader(ParamConstant.FILE_NAME_HEADER).getBytes(), "utf-8");
            }
            fileName = new String(fileName.getBytes("ISO8859-1"), "utf-8");
            //判断文件名是否为空
            if (null == fileName || "".equals(fileName)) {
                return null;
            }
            //路径和文件名
            fileKey = filePath + File.separator + fileName;
        }
        return fileKey;
    }
}
Global site tag (gtag.js) - Google Analytics