Use Java to generate excel and read the content in excel

1. The effect achieved

a, create file effect

b. Reading effect

Second, the required jar package

<dependency>
   <groupId>net.sourceforge.jexcelapi</groupId>
    <artifactId>jxl</artifactId>
    <version>2.6.12</version>
</dependency>

Three, the code snippet

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

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

/**
* @author 
* @createDate
* @Description:  
*/

public class FileTest {
	
	public static void main(String[] args) throws IOException, WriteException {
		String url = "D:\\addressTest.xlsx";
		//创建文件
		//File file = createFiles(url);
		File file = new File(url);
		//创建写工作簿对象
		WritableWorkbook workbook = Workbook.createWorkbook(file);
		//工作表
		WritableSheet sheet = workbook.createSheet("测试地址列表", 0);
		//设置字体
		WritableFont font = new WritableFont(WritableFont.ARIAL,14,WritableFont.BOLD,false,UnderlineStyle.NO_UNDERLINE,Colour.BLACK);
		WritableCellFormat format = new WritableCellFormat(font);
		
		//设置背景颜色
		format.setBackground(Colour.WHITE);
		
		//设置边框
		format.setBorder(Border.ALL, BorderLineStyle.DASH_DOT);
		
		//设置文字居中对齐方式
		format.setAlignment(Alignment.CENTRE);
		
		//设置垂直居中
		format.setVerticalAlignment(VerticalAlignment.CENTRE);
		
		//分别给1,5,6列设置不同的宽度
		sheet.setColumnView(0, 15);
		sheet.setColumnView(4, 65);
		sheet.setColumnView(5, 35);
		
		//给sheet电子版中所有的列设置默认的宽度
		sheet.getSettings().setDefaultColumnWidth(20);
		
		// 给sheet电子版中所有的行设置默认的高度,高度的单位是1/20个像素点,但设置这个貌似就不能        自动换行了
        // sheet.getSettings().setDefaultRowHeight(30 * 20);
		
		//设置自动换行
		format.setWrap(true);
		
		//单元格
		Label label0 = new Label(0,0,"ID",format);
		Label label1 = new Label(1,0,"省",format);
		Label label2 = new Label(2,0,"市",format);
		Label label3 = new Label(3,0,"区",format);
		
		sheet.addCell( label0 );
		sheet.addCell( label1 );
		sheet.addCell( label2 );
		sheet.addCell( label3 );
		
		//给第二行设置背景,字体颜色,对齐方式
		WritableFont font2 = new WritableFont(WritableFont.ARIAL,14,WritableFont.NO_BOLD,false,UnderlineStyle.NO_UNDERLINE,Colour.BLACK);
		WritableCellFormat format2 = new WritableCellFormat();
		
		//设置文字居中对齐方式
		format2.setAlignment(Alignment.CENTRE);
		
		//设置垂直居中
		format2.setVerticalAlignment(VerticalAlignment.CENTRE);
		format2.setBackground(Colour.WHITE);
		format2.setBorder(Border.ALL, BorderLineStyle.THIN);
		format2.setWrap(true);
		
		//记录行数
		int  n = 1;
		
		//查询所有的地址
		List<RegionTest> listRegion = new ArrayList<>();
		listRegion = RegoinTest();
		if(listRegion != null && listRegion.size() > 0){
			for(RegionTest regionTest : listRegion){
				Label lb0 = new Label(0,n,regionTest.getId()+"",format2);
				Label lb1 = new Label(1,n,regionTest.getProvince(),format2);
				Label lb2 = new Label(2,n,regionTest.getCity()+"",format2);
				Label lb3 = new Label(3,n,regionTest.getArea()+"",format2);
				
				sheet.addCell(lb0);
				sheet.addCell(lb1);
				sheet.addCell(lb2);
				sheet.addCell(lb3);
				n++;
			}
		}
		
		workbook.write();
		workbook.close();

		//开始读文件
		InputStream inputStream = new FileInputStream(file);
		try {
			List<List<String>> list = getData(inputStream, 0);
			System.out.println("读取文件的值为:"+JacksonUtil.java2json(list));
		} catch (EncryptedDocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	
	/**
	 * 创建文件(不写东西)
	 * url文件路径
	 * @throws IOException 
	 * */
	public static File createFiles(String url) throws IOException{
		File file = new File(url);
		file.createNewFile();
		return file;
	}
	
	/**
	 * 在excel里面药写入的东西
	 * */
	
	public  static List<RegionTest> RegoinTest(){
		List<RegionTest> listRegoin = new ArrayList<RegionTest>();
		RegionTest region1 = new RegionTest(); 
		region1.setId(1);
		region1.setProvince("广东省");
		region1.setCity("深圳市");
		region1.setArea("福田区");
		listRegoin.add(region1);
		
		RegionTest region2 = new RegionTest();
		region2.setId(2);
		region2.setProvince("广西省");
		region2.setCity("南宁市");
		region2.setArea("直辖区");
		listRegoin.add(region2);
		
		RegionTest region3 = new RegionTest();
		region3.setId(3);
		region3.setProvince("江西省");
		region3.setCity("赣州市");
		region3.setArea("南康区");
		listRegoin.add(region3);
		
		
		RegionTest region4 = new RegionTest();
		region4.setId(4);
		region4.setProvince("江苏省");
		region4.setCity("苏州市");
		region4.setArea("姑苏区");
		listRegoin.add(region4);
		
		RegionTest region5 = new RegionTest();
		region5.setId(5);
		region5.setProvince("上海市");
		region5.setCity("上海市");
		region5.setArea("嘉定区");	
		listRegoin.add(region5);
		
		RegionTest region6 = new RegionTest();
		region6.setId(6);
		region6.setProvince("上海市");
		region6.setCity("上海市");
		region6.setArea("青浦区");	
		listRegoin.add(region6);
		return listRegoin;
	}

/**
	 * 
	 * 读取Excel的内容,第一维数组存储的是一行中格列的值,二维数组存储的是多少个行
	 * 
	 * @param file
	 *            读取数据的源Excel
	 * 
	 * @param ignoreRows
	 *            读取数据忽略的行数,比喻行头不需要读入 忽略的行数为1
	 * 
	 * @return 读出的Excel中数据的内容
	 * 
	 * @throws FileNotFoundException
	 * 
	 * @throws IOException
	 * @throws InvalidFormatException 
	 * @throws EncryptedDocumentException 
	 * 
	 */

	public static List<List<String>> getData(InputStream file, int ignoreRows)

			throws FileNotFoundException, IOException, EncryptedDocumentException, InvalidFormatException {

		List<List<String>> result = new ArrayList<>();

		org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(file);
	    Sheet sheet = workbook.getSheetAt(0);
	    
	    
	    DataFormatter formatter = new DataFormatter();
	    for (Row row : sheet) {
			Iterator<Cell> rowIt = row.iterator();
			
			String rowCell = "";
			List<String> rowsList = new ArrayList<>();
	    	while ( rowIt.hasNext() ) {
	    		Cell cell = rowIt.next();
	            CellReference cellRef = new CellReference(cell.getRow().getRowNum(), cell.getColumnIndex());
	            //单元格名称
	            System.out.print(cellRef.formatAsString());
	            System.out.print(" - ");

	            //通过获取单元格值并应用任何数据格式(Date,0.00,1.23e9,$ 1.23等),获取单元格中显示的文本
	            String text = formatter.formatCellValue(cell);
	            /*System.out.print(text);*/
	            CellType cellType = cell.getCellTypeEnum();
	            cellType.compareTo(CellType.STRING);
	             //获取值并自己格式化
	            	// 字符串型
	            if( cellType.compareTo( CellType.STRING ) == 0 ){
	            	rowCell = cell.getRichStringCellValue().getString();
	            }else if ( cellType.compareTo( CellType.NUMERIC ) == 0 ){
	            	
	            	if (DateUtil.isCellDateFormatted(cell)) { // 如果是date类型则 ,获取该cell的date值
	            		rowCell = cell.getDateCellValue() + "";
	            	} else {// 纯数字
	            		rowCell = cell.getNumericCellValue() + "";
	            	}
	            }else if ( cellType.compareTo( CellType.BOOLEAN ) == 0 ){
	            	rowCell = cell.getBooleanCellValue() + "";
	            }
	            else if ( cellType.compareTo( CellType.FORMULA ) == 0 ){
	            	rowCell = cell.getCellFormula() + "";
	            }
	            else if ( cellType.compareTo( CellType.BLANK ) == 0 ){
	            }
	            else if ( cellType.compareTo( CellType.ERROR ) == 0 ){
	            }else{
	            }
	            System.out.print( rowCell + "  | ");
	            rowsList.add(rowCell);
	    	}
	    	System.out.println();
	    	result.add(rowsList);
	    }
		return result;
	}


}

JXL development Excel document address: https://www.cr173.com/html/10377_1.html 

Reference address: https://www.cnblogs.com/dyh2025/p/9311118.html

Guess you like

Origin blog.csdn.net/qq_36138652/article/details/100039471