java操作excel在开始位置添加一列

java操作excel在开始位置添加一列

首先说一下,我用的JXL(JXL比较简单,但是没有POI功能强大):

jar包:jxl.jar;

没有什么直接的方法可以实现这个功能,我用的是把原先的excel中的内容取出来,放入新的excel,但是从第二列开始存放,从而达到效果,下面是代码...

 

 

package Excel;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import java.io.File;

/**
 * Created by huipu on 2016/11/10.
 */
public class Excel {
    public static void main(String[] args) {
        String url = "C:/Users/huipu/Desktop/表.xls";
        InsertExcelClo(url);


 }
    public static void InsertExcelClo(String url){
        File file = new File(url);
        if(!file.exists()){
            System.out.println("文件不存在");
        }
        Workbook wb = null;
        WritableWorkbook wwb = null;
        try{
            wb = Workbook.getWorkbook(file);
            wwb = Workbook.createWorkbook(file);
            Sheet old_sheet = wb.getSheet(0);
            String old_name = old_sheet.getName();
            int cols = old_sheet.getColumns();
            int rows = old_sheet.getRows();
            WritableSheet new_sheet = wwb.createSheet(old_name,0);
            for(int i = 0;i<rows;i++){
                for(int j = 0;j<cols+1;j++){
                    if(j==0){
                        if(i==0){
                            Label label = new Label(0,0,"xx");
                            new_sheet.addCell(label);
                        }else if(i==1){
                            Label label = new Label(0,1,"xxx");
                            new_sheet.addCell(label);
                        }else {
                            Label label = new Label(0,i,"");
                            new_sheet.addCell(label);
                        }
                    }else {
                        Cell cell = old_sheet.getCell(j-1,i);
                        String str = cell.getContents().equals("")?"":cell.getContents();
                        Label label = new Label(j,i,str);
                        new_sheet.addCell(label);
                    }
                }
            }
            wwb.write();
            System.out.println("修改成功");

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if(wb != null){
                    wb.close();
                }if(wwb != null){
                    wwb.close();
                }
            }catch (Exception e){
                System.out.println("关闭异常");
                e.printStackTrace();
            }
        }


    }

}

 

posted @ 2021-01-23 10:54  冯虚御风,不知所止  阅读(496)  评论(0编辑  收藏  举报