Java read and write excel combat entirely parsed

This article micro-channel public number "AndroidTraveler" episode.

background

A time when graduation season, many graduates entering the workplace.

Therefore, here also wrote a number of technical points novice Android related.

For example, on one of the Android development you need to know those things that cited a number of small points, avoid novice Android developers stepped pit.

At the same time, also coincides with the summer holidays, so students in the holiday period.

This is mainly a question from a college student's.

So here to share my personal problem-solving ideas and methods, hoping to inspire him.

Welcome to the share exchange.

topic

Language: JAVA

Demand: a read table data inside Excel (for example: name + fraction), reordered (by high and low points), and then outputs another Excel spreadsheet.

analysis

General demand we have taken split thinking.
The big problem down into small problems, small problems are solved, the whole big problem will be solved.

The demand is clear, the need to address three questions:

  1. Read the Excel spreadsheet data
  2. Sort data
  3. Write data to another Excel spreadsheet

We here require the use of Java language, the Java language is a very important point is object-oriented.

So we need to think about what this title which we need to create a class.

Probably you need to imagine the following classes:

Read data categories: ExcelReader
write data categories: ExcelWriter
data sorting classes: Since Java API own, making it necessary to repeat the wheel
model class: StudentScore
startup classes: ParserStart, with a main method

Probably UML diagram as follows:

At this point we can write the code v0.1:
ExcelReader.java:

import java.util.List;
public class ExcelReader {
	public List<StudentScore> read(String fileName) {
		//TODO
		return null;
	}
}
复制代码

ExcelWriter.java:

import java.util.List;
public class ExcelWriter {
	public void write(String fileName, List<StudentScore> list) {
		//TODO
	}
}
复制代码

StudentScore.java:

public class StudentScore {
	private String name;
	private int score;
	
	public StudentScore(String name, int score) {
		super();
		this.name = name;
		this.score = score;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getScore() {
		return score;
	}
	public void setScore(int score) {
		this.score = score;
	}
}
复制代码

ParserStart.java:

import java.util.List;

public class ParserStart {
	public static void main(String[] args) {
		// 第一步:读取数据
		List<StudentScore> dataList = new ExcelReader().read("input.xls");
		// 第二步:排序
		//TODO
		// 第三部:写入数据
		new ExcelWriter().write("output.xls", dataList);
	}
}
复制代码

Well, setting up the basic framework. Then step by step to achieve our approach.

v0.2 Code: perfect read method of ExcelReader

Excel reading methods you can use third-party libraries, so we do not need to write their own.
Here we use a third-party provided Apache POI library.
Download link address: poi.apache.org/download.ht...
use to the time of this writing is version 4.1.0
unzip the package and then the jar can be introduced into the Eclipse project.

The next step is to write the actual code, as detailed comments.

Our sample file to read as follows:

ExcelReader.java:

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.EncryptedDocumentException;
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;

public class ExcelReader {
	public List<StudentScore> read(String fileName) throws EncryptedDocumentException, IOException {
		if (fileName == null) return null;
		
		File xlsFile = new File(fileName);
		if (!xlsFile.exists()) return null;
		
		// 工作表
		Workbook workbook = WorkbookFactory.create(xlsFile);
		// 表个数
		int numberOfSheets = workbook.getNumberOfSheets();
//		System.out.println(numberOfSheets);
		if (numberOfSheets <= 0) return null;
		
		List<StudentScore> list = new ArrayList<>();
		//我们的需求只需要处理一个表,因此不需要遍历
		Sheet sheet = workbook.getSheetAt(0);
		// 行数
		int rowNumbers = sheet.getLastRowNum() + 1;
//		System.out.println(rowNumbers);
		StudentScore score;
		// 读数据,第二行开始读取
		for (int row = 1; row < rowNumbers; row++) {
			Row r = sheet.getRow(row);
//			System.out.println(r.getPhysicalNumberOfCells());
			//我们只需要前两列
			if (r.getPhysicalNumberOfCells() >= 2) {
				score = new StudentScore(r.getCell(0).toString(), (int) Double.parseDouble(r.getCell(1).toString()));
				list.add(score);
			} 
		}
		return list;
	}
}
复制代码

v0.3 Code: doing the sorting processing of the data read

In the v0.2 release, we successfully read the data, but the data we read in the order in which Excel, so we need to do the sorting process. Java library there are ways to rank the set. But we need to Model additional processing, add sorting rules. Because sorting may be from small to large, it can be ranked from largest to smallest.

StudentScore.java:

public class StudentScore implements Comparable<StudentScore>{
	
	private String name;
	private int score;
	
	public StudentScore(String name, int score) {
		super();
		this.name = name;
		this.score = score;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getScore() {
		return score;
	}
	public void setScore(int score) {
		this.score = score;
	}
	
	@Override
	public String toString() {
		return "StudentScore [name=" + name + ", score=" + score + "]";
	}
	
	@Override
	public int compareTo(StudentScore o) {
		return o.score - this.score;
	}
	
}
复制代码

ParserStart.java:

import java.util.Collections;
import java.util.List;

public class ParserStart {

	public static void main(String[] args) throws Exception{
		// 第一步:读取数据
		List<StudentScore> dataList = new ExcelReader().read("resource/input.xls");
		System.out.println(dataList);
		// 第二步:排序
		Collections.sort(dataList);
		System.out.println(dataList);
		// 第三部:写入数据
//		new ExcelWriter().write("output.xls", dataList);
	}

}
复制代码

v0.4 Code: The sorted data is written in another table excel

In the v0.3 release, we completed the sequencing data, then we need to be sorted rows of data written in output.xls.

ExcelWriter.java

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class ExcelWriter {

	public void write(String fileName, List<StudentScore> list) throws IOException {
		HSSFWorkbook workbook = new HSSFWorkbook();

		HSSFSheet sheet = workbook.createSheet("StudentScore");

		// 创建Excel标题行,第一行
		HSSFRow headRow = sheet.createRow(0);
		headRow.createCell(0).setCellValue("姓名");
		headRow.createCell(1).setCellValue("分数");

		// 往Excel表中遍历写入数据
		for (StudentScore studentScore : list) {
			createCell(studentScore, sheet);
		}

		File xlsFile = new File(fileName);
		System.out.println("xlsFile exist="+xlsFile.exists());
		System.out.println("xlsFile exist="+xlsFile.getAbsolutePath());
		workbook.write(xlsFile);// 或者以流的形式写入文件 workbook.write(new FileOutputStream(xlsFile));
		workbook.close();
	}

	// 创建Excel的一行数据。
	private void createCell(StudentScore studentScore, HSSFSheet sheet) {
		HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
		dataRow.createCell(0).setCellValue(studentScore.getName());
		dataRow.createCell(1).setCellValue(studentScore.getScore());
	}

}
复制代码

ParserStart.java

import java.util.Collections;
import java.util.List;

public class ParserStart {

	public static void main(String[] args) throws Exception {
		// 第一步:读取数据
		List<StudentScore> dataList = new ExcelReader().read("resource/input.xls");
		System.out.println(dataList);
		// 第二步:排序
		Collections.sort(dataList);
		System.out.println(dataList);
		// 第三部:写入数据
		new ExcelWriter().write("resource/output.xls", dataList);
	}

}
复制代码

This, by several versions of iterations, our demand is fulfilled.

NOTE:
In this project, input.xls on resource folder. So the final version passed in the path is resource / input.xls. In addition, when the output side found Eclipse does not show up output.xls, need to refresh it.
In addition, when you download my project run verification, you may need to be modified under the JRE.
Also jar package not to introduce the wrong place:

Of course, there are several points need to be perfect description below:

  1. There is no check on the legality of doing data entry table, such as the case of the score is negative if the operation needs to be done some tips and the like.
  2. When the file does not exist here is determined directly returns null. And there is no file to determine whether the excel file. Here it is handed over to you perfect. And the exception is not here to do the processing, direct throws.
  3. We do not do here because of the simple abstract. However, the possible need to read and write word or pdf or other documents, it is possible to consider the introduction of inheritance and polymorphism. Extracting the base class.
  4. Rational organization of folders and naming.

Also talk about what scenarios it, in fact, really have.

Mobile end multi-language, imagine excel sheet products to you with a multi-language.
If you a copy of a multiple language resource file under, it is hard to imagine efficiency.
And if you use the content of this section, every minute read excel output to the console assembly in accordance with the rules you want.
Think a little 6 ah.
Well, this issue is over, welcome message exchanges and discussions.

If you have knowledge want to know, please leave a message No. public private letter, maybe next pick is you.

Source acquire Address:
github.com/nesger/Java...

Reference links:
Java to read Excel data: based on Apache POI (a)
Java read and parse Excel data: based on Apache POI (b)
write Java to export data to an Excel spreadsheet rows: based on Apache POI

Guess you like

Origin juejin.im/post/5d2bcf03e51d45778f076dce