java操作excel文件

来源:互联网 发布:b2b发布信息软件 编辑:程序博客网 时间:2024/06/11 09:38

相关jar包下载地址:点击打开链接

import jxl.Sheet;import jxl.Workbook;import jxl.read.biff.BiffException;import jxl.write.WritableWorkbook;import jxl.write.WriteException;import org.apache.poi.hssf.record.formula.functions.Row;import org.apache.poi.hssf.usermodel.HSSFRichTextString;import org.apache.poi.hssf.usermodel.HSSFRow;import org.apache.poi.hssf.usermodel.HSSFSheet;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.poifs.filesystem.POIFSFileSystem;import java.io.*;import static jxl.Workbook.getWorkbook;public class Main {    public static void main(String[] args) {        String oldFilePath="D:/TGTest/TG.xlsx";   //原Excel文件所在路径        String newFilePath= "D:/TGTest/2.xls";  //新建的Excel文件所在路径//        Boolean bl= validateExcel(newFilePath);      //验证文件是否存在 格式是否正确//        Boolean bool= validateExcel(oldFilePath);////        if(bl){//              deleteFile(newFilePath);              //删除已经存在的同名excel文件//              newExcel(newFilePath);           //新建excel表格//        }//        if(bool) {//             readExcel(oldFilePath);            //读取excel表格内容 文件后缀必须为.xls//             copyExcel(oldFilePath, newFilePath);    //拷贝excel表格内容//            addExcel(newFilePath, oldFilePath);     //追加数据到"D:/TGTest/TG1.xls"文件//        }    }    /*使用poi新建一个文件夹*/    public static void newExcel(String filePath){        System.out.print("开始新建一个Excel文件...");        try {            HSSFWorkbook workbook = new HSSFWorkbook();            FileOutputStream fileOut = new FileOutputStream(filePath);            workbook.write(fileOut);            fileOut.close();        } catch (IOException e) {            e.printStackTrace();            System.out.print("Excel文件创建失败!"+e.getMessage());        }        System.out.print("Excel文件创建成功!");    }    /*使用jxl读取Excel文件内容(只能读取Excel2003的 <即后缀为 .xls的文件>  注:读取时文件必须是关闭状态)*/    public static void readExcel(String filePath){        System.out.println("开始读取" + filePath + "文件...");        File file = new File(filePath);        // 创建输入流,读取Excel        InputStream is = null;        try {         is = new FileInputStream(file.getAbsolutePath());        // jxl提供的Workbook类        Workbook wb = getWorkbook(is);        // Excel的页签数量        int sheet_size = wb.getNumberOfSheets();        for (int index = 0; index < sheet_size; index++) {            // 每个页签创建一个Sheet对象            Sheet sheet = wb.getSheet(index);            // sheet.getRows()返回该页的总行数            for (int i = 0; i < sheet.getRows(); i++) {                // sheet.getColumns()返回该页的总列数                for (int j = 0; j < sheet.getColumns(); j++) {                    String cellinfo = sheet.getCell(j, i).getContents();                    System.out.println((i+1)+ "行" +(j+1)+ "列:" +cellinfo);                }            }        }        } catch (FileNotFoundException e) {            e.printStackTrace();            System.out.println("文件读取失败"+e.getMessage());        } catch (BiffException e) {            e.printStackTrace();            System.out.println("文件读取失败" + e.getMessage());        } catch (IOException e) {            e.printStackTrace();            System.out.println("文件读取失败" + e.getMessage());        }        System.out.println("文件读取结束!");    }    /*拷贝表格中数据到另一个Excel表格*/    public static  void copyExcel(String oldFilePath,String newFilePath ){        System.out.println("从"+oldFilePath+"文件拷贝至"+newFilePath+"开始...");        Workbook workbook =null;        WritableWorkbook writableWorkbook =null;            try {               workbook = getWorkbook(new File(oldFilePath));                Sheet sheet = workbook.getSheet(0); //获得第一个工作表对象                writableWorkbook = Workbook.createWorkbook(new File(newFilePath));             // writableWorkbook = Workbook.createWorkbook(new File(oldFilePath),workbook);   拷贝整个Excel                //创建第一个工作表对象,名为("Sheet1")                writableWorkbook.importSheet("Sheet1", 0,sheet);                writableWorkbook.write();                writableWorkbook.close();                workbook.close();            } catch (BiffException e) {                e.printStackTrace();                System.out.println("文件拷贝失败" + e.getMessage());            } catch (IOException e) {                e.printStackTrace();                System.out.println("文件拷贝失败" + e.getMessage());            } catch (WriteException e) {                e.printStackTrace();                System.out.println("文件拷贝失败" + e.getMessage());            }        System.out.println("文件拷贝结束!");        }    /*判断文件是否存在,以及版本是否是2003的*/    public static boolean validateExcel(String filePath) {        /** 检查文件名是否为空或者是否是Excel格式的文件 */        if (filePath == null || !(WDWUtil.isExcel2003(filePath) || WDWUtil .isExcel2007(filePath))) {            System.out.println("文件名不是excel格式");            return false;        }        /** 检查文件是否存在 */        File file = new File(filePath);        if (!file.exists()) {            System.out.println( "文件不存在");            return false;        }        return true;    }    /*删除文件*/    public static void deleteFile(String filePath){        File file = new File(filePath);        // 判断目录或文件是否存在        if (!file.exists()) {  // 不存在返回 false          System.out.println("文件不存在");        } else {            // 判断是否为文件            if (file.isFile()) {  // 为文件时调用删除文件方法                file.delete();                System.out.println("文件已删除");            }        }    }    /*在newfilePath中追加数据*/    public static void addExcel(String newfilePath,String oldfilePath){        System.out.println("开始追加数据...");        FileInputStream fs= null;  //获取d://test.xls        try {        fs = new FileInputStream(oldfilePath);        POIFSFileSystem ps=new POIFSFileSystem(fs);  //使用POI提供的方法得到excel的信息        HSSFWorkbook wb=new HSSFWorkbook(ps);        HSSFSheet sheet=wb.getSheetAt(0);  //获取到工作表,因为一个excel可能有多个工作表        HSSFRow row=sheet.getRow(0);  //获取第一行(excel中的行默认从0开始,所以这就是为什么,一个excel必须有字段列头),即,字段列头,便于赋值        System.out.println(sheet.getLastRowNum()+" "+row.getLastCellNum());  //分别得到最后一行的行号,和一条记录的最后一个单元格        FileOutputStream out=new FileOutputStream(oldfilePath);  //向oldfilePath中写数据        row=sheet.createRow((short)(sheet.getLastRowNum()+1)); //在现有行号后追加数据        row.createCell(0).setCellValue("leilei"); //设置第一个(从0开始)单元格的数据        row.createCell(1).setCellValue(24); //设置第二个(从0开始)单元格的数据        out.flush();        wb.write(out);        out.close();        System.out.println(row.getPhysicalNumberOfCells()+" "+row.getLastCellNum());        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        System.out.println("数据追加结束!");    }} /*验证文件格式*/class WDWUtil {    public static boolean isExcel2003(String filePath) {        System.out.println("2003");        return filePath.matches("^.+\\.(?i)(xls)$");   //判断excel文件是否为2003版本    }    public static boolean isExcel2007(String filePath) {        System.out.println("2007");        return filePath.matches("^.+\\.(?i)(xlsx)$");   //判断excel文件是否为2007版本    }}


原创粉丝点击