zoukankan      html  css  js  c++  java
  • java从Excle中读取数据,导出到另一个Excle中

    pom.xml:

    <dependency>
        <groupId>net.sourceforge.jexcelapi</groupId>
        <artifactId>jxl</artifactId>
        <version>2.6.12</version>
    </dependency>
    <dependency>
        <groupId>net.sf.jxls</groupId>
        <artifactId>jxls-core</artifactId>
        <version>1.0.6</version>
    </dependency>
    ExcelReaderUtil:
    package com.baosight.wisdomsf.lite.persist.system.syndata.util;
    
    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.DataFormatter;
    import org.apache.poi.ss.usermodel.DateUtil;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Sheet;
    import org.apache.poi.ss.usermodel.Workbook;
    import org.apache.poi.ss.usermodel.WorkbookFactory;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    /**
     * @author YuanPeng
     */
    public class ExcelReaderUtil {
    
    
        private String filePath;
        private String sheetName;
        private Workbook workBook;
        private Sheet sheet;
        private List<String> columnHeaderList;
        private List<List<String>> listData;
        private List<Map<String,String>> mapData;
        private boolean flag;
    
        public ExcelReaderUtil(String filePath, String sheetName) {
            this.filePath = filePath;
            this.sheetName = sheetName;
            this.flag = false;
            this.load();
        }
    
        public Map<String, String> getAllData(){
            Map<String, String> map = new HashMap();
            String prefix = "LEFT("";
            String suffix = "",19)";
            for(int i = 0; i < listData.size(); i++){
                List<String> list = listData.get(i);
                List<String> list1 = new ArrayList();
                for(int j = 0; j < list.size(); j++){
                    String str = list.get(j);
                    if(str.startsWith(prefix) && str.endsWith(suffix)){
                        str = str.substring(prefix.length(), str.lastIndexOf(suffix));
                    }
                    list1.add(str);
                }
                map.put(list1.get(0), list.get(1));
            }
            return map;
        }
    
        private void load() {
            FileInputStream inStream = null;
            try {
                inStream = new FileInputStream(new File(filePath));
                workBook = WorkbookFactory.create(inStream);
                sheet = workBook.getSheet(sheetName);
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                try {
                    if(inStream!=null){
                        inStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
        private String getCellValue(Cell cell) {
            String cellValue = "";
            DataFormatter formatter = new DataFormatter();
            if (cell != null) {
                switch (cell.getCellType()) {
                    case Cell.CELL_TYPE_NUMERIC:
                        if (DateUtil.isCellDateFormatted(cell)) {
                            cellValue = formatter.formatCellValue(cell);
                        } else {
                            double value = cell.getNumericCellValue();
                            int intValue = (int) value;
                            cellValue = value - intValue == 0 ? String.valueOf(intValue) : String.valueOf(value);
                        }
                        break;
                    case Cell.CELL_TYPE_STRING:
                        cellValue = cell.getStringCellValue();
                        break;
                    case Cell.CELL_TYPE_BOOLEAN:
                        cellValue = String.valueOf(cell.getBooleanCellValue());
                        break;
                    case Cell.CELL_TYPE_FORMULA:
                        cellValue = String.valueOf(cell.getCellFormula());
                        break;
                    case Cell.CELL_TYPE_BLANK:
                        cellValue = "";
                        break;
                    case Cell.CELL_TYPE_ERROR:
                        cellValue = "";
                        break;
                    default:
                        cellValue = cell.toString().trim();
                        break;
                }
            }
            return cellValue.trim();
        }
    
        private void getSheetData() {
            listData = new ArrayList<List<String>>();
            mapData = new ArrayList<Map<String, String>>();
            columnHeaderList = new ArrayList<String>();
            int numOfRows = sheet.getLastRowNum() + 1;
            for (int i = 0; i < numOfRows; i++) {
                Row row = sheet.getRow(i);
                Map<String, String> map = new HashMap<String, String>();
                List<String> list = new ArrayList<String>();
                if (row != null) {
                    for (int j = 0; j < row.getLastCellNum(); j++) {
                        Cell cell = row.getCell(j);
                        if (i == 0){
                            columnHeaderList.add(getCellValue(cell));
                        }
                        else{
                            map.put(columnHeaderList.get(j), this.getCellValue(cell));
                        }
                        list.add(this.getCellValue(cell));
                    }
                }
                if (i > 0){
                    mapData.add(map);
                }
                listData.add(list);
            }
            flag = true;
        }
    
        public String getCellData(int row, int col){
            if(row<=0 || col<=0){
                return null;
            }
            if(!flag){
                this.getSheetData();
            }
            if(listData.size()>=row && listData.get(row-1).size()>=col){
                return listData.get(row-1).get(col-1);
            }else{
                return null;
            }
        }
    
        public String getCellData(int row, String headerName){
            if(row<=0){
                return null;
            }
            if(!flag){
                this.getSheetData();
            }
            if(mapData.size()>=row && mapData.get(row-1).containsKey(headerName)){
                return mapData.get(row-1).get(headerName);
            }else{
                return null;
            }
        }
    
    }

    调用测试方法:

    ExcelReader:
    package com.baosight.wisdomsf.lite.persist.system.syndata.util;
    
    import com.baosight.wisdomsf.lite.utils.DateUtils;
    import jxl.Cell;
    import jxl.Sheet;
    import jxl.Workbook;
    import jxl.read.biff.BiffException;
    import jxl.write.Label;
    import jxl.write.WritableCellFormat;
    import jxl.write.WritableFont;
    import jxl.write.WritableSheet;
    import jxl.write.WritableWorkbook;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.Map;
    
    /**
     * @author YuanPeng
     */
    public class ExcelReader {
    
        public static void main(String[] args) throws Exception {
    
            String filePath = "C:\Users\Lenovo\Desktop\测试读取文件\机构信息.xls";
            String filePath2 = "C:\Users\Lenovo\Desktop\测试读取文件\机构信息备份.xls";
    
            createBackUpDir(filePath,filePath2,true);
        }
    
    
        public static void createBackUpDir(String filePath,String newFilePath,boolean oldDeleteFlag) throws Exception {
            if(filePath != null && !"".equals(filePath) && newFilePath != null && !"".equals(newFilePath)){
                File oldFile = new File(filePath);
                //获取原文件的文件名
                String fileName = oldFile.getName();
                //备份文件路径加上日期路径用来区分
                newFilePath = newFilePath + File.separator + DateUtils.dateTime() + File.separator + fileName;//获取备份的文件路径
                File dir = new File(newFilePath);
                File parent = dir.getParentFile();
                if (dir != null && !parent.exists()) {//创建目录
                    //System.out.println("创建目录start...");
                    parent.mkdirs();
                    //System.out.println("创建目录over...");
                }
                //读取原文件的内容写入新文件
                ExcelReaderUtil eh = new ExcelReaderUtil(filePath, "SQL Results");
                eh.getCellData(1,1);
                Map<String, String> map = eh.getAllData();
                // Excel获得文件
                Workbook workBook = Workbook.getWorkbook(new File(filePath));
                // 打开一个文件的副本,并且指定数据写回到原文件
                WritableWorkbook book = Workbook.createWorkbook(new File(newFilePath), workBook);
    
                Sheet sheet = book.getSheet(0);
                WritableSheet wsheet = book.getSheet(0);
                int colunms = sheet.getColumns();
                for (int i = 0; i < sheet.getRows(); i++) {
                    String number = sheet.getCell(4, i).getContents().trim();
                    if(map.containsKey(number)){
                        Cell cell = wsheet.getCell(13, i);
                        String address = cell.getContents().trim();
                        if(address == null  || "".equals(address)){
                            Label label = new Label(colunms, i, map.get(number), getDataCellFormat());
                            wsheet.addCell(label);
                        }
                    }
                }
                book.write();
                book.close();
    
                //备份完毕之后将原来的文件删掉
                if(oldDeleteFlag){
                    oldFile.delete();
                }
            }
        }
    
        public static WritableCellFormat getDataCellFormat() {
            WritableFont wf = new WritableFont(WritableFont.TIMES, 10, WritableFont.BOLD, false);
            WritableCellFormat wcf = new WritableCellFormat(wf);
            return wcf;
        }
    
    }
    原:科技改变生活!
  • 相关阅读:
    OpenGL纹理映射总结
    研究生常用网站:
    Oracle 11g,10g数据库软件下载地址
    <转>乔布斯羡慕嫉妒恨的人:Android之父安迪·鲁宾
    VC6里面的中文名字或者注释复制乱码解决
    基于CentOs的Hadoop集群全分布式部署<转>
    centos架设FTP服务器
    centos 卸载 jdk
    ESX的 企业版许可证
    vsftpd的 553 Could not create file
  • 原文地址:https://www.cnblogs.com/iyuanpeng/p/15523981.html
Copyright © 2011-2022 走看看