java读取excel获取数据写入到另外一个excel

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.nihaorz</groupId>
    <artifactId>excel_hezhan</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>net.sf.jxls</groupId>
            <artifactId>jxls-core</artifactId>
            <version>1.0.6</version>
        </dependency>
        <dependency>
            <groupId>net.sourceforge.jexcelapi</groupId>
            <artifactId>jxl</artifactId>
            <version>2.6.12</version>
        </dependency>
    </dependencies>

</project>

  

ExcelReader.java

package com.nihaorz;

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;

public class ExcelReader {

    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 ExcelReader(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;
        }
    }

}

  

ExcelTest.java

package com.nihaorz;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
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.util.Map;

public class ExcelTest {

    public static void main(String[] args) throws Exception {
        ExcelReader eh = new ExcelReader("C:\\Users\\Nihaorz\\Desktop\\贺站.xlsx", "Sheet1");
        eh.getCellData(1,1);
        Map<String, String> map = eh.getAllData();

        String filePath = "C:\\Users\\Nihaorz\\Desktop\\待修改.xls";
        // Excel获得文件
        Workbook workBook = Workbook.getWorkbook(new File(filePath));
        // 打开一个文件的副本,并且指定数据写回到原文件
        WritableWorkbook book = Workbook.createWorkbook(new File(filePath), 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();
    }

    public static WritableCellFormat getDataCellFormat() {
        WritableFont wf = new WritableFont(WritableFont.TIMES, 10, WritableFont.BOLD, false);
        WritableCellFormat wcf = new WritableCellFormat(wf);
        return wcf;
    }

}

  

时间: 2024-10-08 08:10:49

java读取excel获取数据写入到另外一个excel的相关文章

Java学习-022-Properties 文件数据写入

Properties 配置文件写入主要通过 Properties.setProperty 和 Properties.store 两个方法,此文以一个简单的 properties 文件写入源码做示例. 小二上码...若有不足之处,敬请大神指正,不胜感激! Properties 文件写入源码如下所示: 1 /** 2 * @function write data to text file by Properties 3 * 4 * @author Aaron.ffp 5 * @version V1.

python 读取excel数据插入到另外一个excel

#-*-coding:utf-8-*- import xlrd import xlwt def excel_copy(dir_from, dir_to, sheet_name): '''从一个excel写入到另外一个excel''' wb = xlrd.open_workbook(dir_from) # 选择sheet页 sheet1 = wb.sheet_by_index(0) # 打印每个sheet页的行数 # print("sheet1行数:%d" % sheet1.nrows)

Java读取txt文件和写入txt文件

写Java程序时经常碰到要读如txt或写入txt文件的情况,但是由于要定义好多变量,经常记不住,每次都要查,特此整理一下,简单易用,方便好懂! package edu.thu.keyword.test; import java.io.File; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream;

Java从控制台获取数据的方法

一.使用System.in.read()一次获取一个字节 输入再多数据,只会获取第一个字节的int形式.获取的是字节,而不是字符,所以如果输入中文字符,强转后会得到乱码 1 try { 2 int in_num=System.in.read(); //获取的是一个字节的int类型 3 System.out.println("强转前:"+in_num); 4 System.out.println("强转后:"+(char)in_num); 5 } catch (IOE

用Excel获取数据——不仅仅只是打开表格

引言:看到标题,你是否有些困惑?在Excel上具备数据获取的能力是指什么?难道不是把csv格式的表格和Excel格式的表格打开就好了吗?然而并非这样.本文选自<数据化运营速成手册>. 其实标题中有两层意思:第一层意思是在一些数据库管理不那么严格的中小型企业,可以通过Excel中的ODBC数据接口,与数据库或者数据仓库建立连接,直接快速取数,提高工作效率:第二层意思是Excel 2016中有相当强大的数据获取工具,即便不能从数据库直接获取,也能从多个本地的数据表中将数据抽取.整理和转化,并做到实

Java读取操作大数据excel

工作需要,读取大数据量的excel.用Apache poi的普通模式读取,会抛内存溢出.查询文档得知有另外一种模式--用户模式.该模式不会一下子整个文件load进来放在内存里,而是一行一行的读取,这样就能避免内存溢出了. 上码: package com.ism.excel.pkg07; import java.io.InputStream; import java.sql.SQLException; import java.util.ArrayList; import java.util.Ite

转:Java读取txt文件和写入txt文件

1 package edu.thu.keyword.test; 2 3 import java.io.File; 4 import java.io.InputStreamReader; 5 import java.io.BufferedReader; 6 import java.io.BufferedWriter; 7 import java.io.FileInputStream; 8 import java.io.FileWriter; 9 10 public class cin_txt {

[PHP] java读取PHP接口数据

和安卓是一个道理,读取json数据 PHP文件: <?php class Test{ //日志路径 const LOG_PATH="E:\phpServer\Apache\logs\\error.log"; //显示的行数 const PAGES=50; public static function main(){ header("content-type:text/html;charset=utf-8"); if(!empty($_GET['action']

PHP中Post和Get获取数据写入文件中

有时候Post或者Get传过来的数据我们不知道它是个什么样的形式,它可能是JSON格式或者就是简单提交过来的数据,这时候我们可以把他写入到文本中,就可以看到传过来的数据是什么格式了. $val = ""; $currentDateTime = date('YmdHis',time()); $currentDate = date('Ymd',time()); $fileName = "ioslog/".$currentDate;//文件名称 @$data = fope