Java 简单的excel读写操作

摘要:
设置excel工作表值cell.setCellValue;wb.write;output.flush();output.close();}/*//创建单元格对象CellCellCell0=行。带有行对象的createCell;Cellcell1=row.createCell;Cellcell2=row.createCell;//使用单元格对象进行读写。
描述:简单的对excel的第一个Sheet表的读写操作

依赖包:apache.poi/poi-3.14、apache.poi/poi-ooxml-3.14

package excel;

import org.apache.poi.hssf.usermodel.HSSFCell;
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 org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static okhttp3.internal.http.HttpDate.format;


public class excelTest1 {
    public String path = System.getProperty("user.dir") + "/src/main/resources/excelTest.xls";
    public String path1 = System.getProperty("user.dir") + "/src/main/resources/excelTest.xlsx";
    public String path2 = "C:\Users\Desktop\基线脚本维护.xlsx";
    public final static String DATE_OUTPUT_PATTERNS = "yyyy-MM-dd";
    public final static SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
            DATE_OUTPUT_PATTERNS);

    @Test
    public void createExcelTest() throws Exception {
        excelTest1 ce = new excelTest1();
        //ce.createExcelxls(path);
        ce.createExcelxlsx(path1);
    }

    @Test
    public void getExcelTest() throws Exception{
        excelTest1 ce = new excelTest1();
        ce.getExcelxlsx(path2);
    }



    //创建excel.xls
    public void createExcelxls(String path) throws Exception {
        //创建excel对象
        HSSFWorkbook wb = new HSSFWorkbook();
        //用文件对象创建sheet对象
        HSSFSheet sheet = wb.createSheet("这是第一个sheet页");
        //用sheet对象创建行对象
        HSSFRow row = sheet.createRow(0);
        //创建单元格样式
        CellStyle cellStyle = wb.createCellStyle();
        //用行对象创建单元格对象Cell
        Cell cell = row.createCell(0);
        //用cell对象读写。设置excel工作表值
        cell.setCellValue(1);
        FileOutputStream output = new FileOutputStream(path);
        wb.write(output);
        output.flush();
    }

    //创建excel.xlsx
    public void createExcelxlsx(String path) throws Exception {
        //创建excel对象
        XSSFWorkbook wb = new XSSFWorkbook();
        //用文件对象创建sheet对象
        XSSFSheet sheet = wb.createSheet("这是第一个sheet页");
        //用sheet对象创建行对象
        XSSFRow row = sheet.createRow(0);
        //创建单元格样式
        CellStyle cellStyle = wb.createCellStyle();

        //构造数据
        List<Object> list = new ArrayList<>();
        list.add("这是String");
        list.add(1);
        list.add(getDate());
        int length = list.size();

        for(int n=0;n<length;n++){
            FileOutputStream output = new FileOutputStream(path);
            //用行对象创建单元格对象Cell
            Cell cell = row.createCell(n);
            //用cell对象读写。设置excel工作表值
            cell.setCellValue(list.get(n).toString());
            wb.write(output);
            output.flush();
            output.close();
        }
        /*//用行对象创建单元格对象Cell
        Cell cell0 = row.createCell(0);
        Cell cell1 = row.createCell(0);
        Cell cell2 = row.createCell(0);
        //用cell对象读写。设置excel工作表值
        cell0.setCellValue(1);
        cell1.setCellValue("这是String");
        cell2.setCellValue(getDate());
        FileOutputStream output = new FileOutputStream(path);
        wb.write(output);
        output.flush();
        output.close();*/
    }

    //读取Excel.xls文件的值
    public void getExcelxls(String path) throws Exception{
        POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(path));
        //得到excel工作簿对象
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        //得到sheet页个数(从1开始数,但是取值的时候要从index=0开始)
        int scount = wb.getNumberOfSheets();
        System.out.println("sheet页的个数为:"+scount);
        for (int a =0;a<scount;a++){
            String sheetName = wb.getSheetName(a);
            System.out.println("第"+(a+1)+"个sheet页的名字为"+sheetName+",内容如下:");
            //得到excel工作表对象(0代表第一个sheet页)
            HSSFSheet sheet = wb.getSheetAt(a);
            HSSFSheet sheet1 = wb.getSheet("第一个sheet页");
            //预定义单元格的值
            String c = "";
            //得到工作表的有效行数(行数从0开始数,取值是从index=0开始)
            int rcount = sheet.getLastRowNum();
            System.out.println("第"+(a+1)+"个sheet页有"+rcount+"行");
            for(int i=0;i<rcount;i++){
                //得到excel工作表的行
                HSSFRow row = sheet.getRow(i);
                if(null!=row){
                    //获取一行(row)的有效单元格(cell)个数(列数从1开始数,取值的时候从index=0开始取)
                    int ccount = row.getLastCellNum();
                    System.out.println("第"+(i+1)+"行有"+ccount+"个单元格");
                    for(int j=0;j<ccount;j++){
                        //得到excel工作表指定行的单元格
                        HSSFCell cell = row.getCell(j);
                        if(null!=cell){
                            //得到单元格类型
                            int cellType = cell.getCellType();
                            switch (cellType){
                                case HSSFCell.CELL_TYPE_STRING:
                                    c = cell.getStringCellValue();
                                    if(c.trim().equals("")||c.trim().length()<=0)
                                        c="";
                                    break;
                                case HSSFCell.CELL_TYPE_NUMERIC:
                                    c = String.valueOf(cell.getNumericCellValue());
                                default:
                                    break;
                            }
                            //String c = cell.getStringCellValue();
                            System.out.println("第"+(i+1)+"行"+(j+1)+"列的值为:"+c+" ");
                        }else {
                            System.out.println("第"+(i+1)+"行"+(j+1)+"列的值为空"+" ");
                        }
                    }
                    System.out.println();
                }else {
                    System.out.println("第"+(i+1)+"行的值为空");
                }
            }
        }
    }

    //读取Excel.xlsx文件的值
    public void getExcelxlsx(String path) throws Exception{
        //得到excel工作簿对象
        XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(path));
        //得到sheet页个数(从1开始数,但是取值的时候要从index=0开始)
        int scount = wb.getNumberOfSheets();
        System.out.println("sheet页的个数为:"+scount);
        for (int a =0;a<scount;a++){
            String sheetName = wb.getSheetName(a);
            System.out.println("第"+(a+1)+"个sheet页的名字为"+sheetName+",内容如下:");
            //得到excel工作表对象(0代表第一个sheet页)
            XSSFSheet sheet = wb.getSheetAt(a);
            XSSFSheet sheet1 = wb.getSheet("第一个sheet页");
            //预定义单元格的值
            String c = "";
            //得到工作表的有效行数(行数从0开始数,取值是从index=0开始)
            int rcount = sheet.getLastRowNum();
            System.out.println("第"+(a+1)+"个sheet页有"+rcount+"行");
            for(int i=0;i<rcount;i++){
                //得到excel工作表的行
                XSSFRow row = sheet.getRow(i);
                if(null!=row){
                    //获取一行(row)的有效单元格(cell)个数(列数从1开始数,取值的时候从index=0开始取)
                    int ccount = row.getLastCellNum();
                    System.out.println("第"+(i+1)+"行有"+ccount+"个单元格");
                    for(int j=0;j<ccount;j++){
                        //得到excel工作表指定行的单元格
                        XSSFCell cell = row.getCell(j);
                        if(null!=cell){
                            //得到单元格类型
                            int cellType = cell.getCellType();
                            switch (cellType){
                                case HSSFCell.CELL_TYPE_STRING:
                                    c = cell.getStringCellValue();
                                    if(c.trim().equals("")||c.trim().length()<=0)
                                        c="";
                                    break;
                                case HSSFCell.CELL_TYPE_NUMERIC:
                                    //如果是日期类型,需要时间转换
                                    if(DateUtil.isCellDateFormatted(cell)){
                                        Date theDate = cell.getDateCellValue();
                                        c = simpleDateFormat.format(theDate);
                                    }else {
                                        c = String.valueOf(cell.getNumericCellValue());
                                    }

                                default:
                                    break;
                            }
                            //String c = cell.getStringCellValue();
                            System.out.println("第"+(i+1)+"行"+(j+1)+"列的值为:"+c+" ");
                        }else {
                            System.out.println("第"+(i+1)+"行"+(j+1)+"列的值为空"+" ");
                        }
                    }
                    System.out.println();
                }else {
                    System.out.println("第"+(i+1)+"行的值为空");
                }
            }
        }
    }

    //获取时间
    public String getDate() {
        Date d = new Date();
        System.out.println(d);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentTime = sdf.format(d);
        System.out.println(currentTime);
        return currentTime;
    }

    @Test
    public void fun(){
        Date d = new Date();
        System.out.println(d);
    }
}

免责声明:文章转载自《Java 简单的excel读写操作》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇数据结构基础之memset---有memset 抛出的int 和 char 之间的转换和字节对齐使用Database Control访问数据库问题解决了下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Visual C# 制作DLL文件

一、制作.dll1.首先创建一个新类库工程文件  文件->新建->项目->Visual C#->类库。填入工程文件名称,并且选择文件要存放的目录。 2.工程文件 将Class1.cs改名自己要创建的文件名:Operate.cs,并填入代码。 3.生成DLL文件 生成->生成myDll.dll,最后会在工程文件的bindebug...

vbscript 中对excel常见操作

 vbs 对excel的操作 删除、修改单元格,设置字体、背景色dim oExcel,oWb,oSheet Set oExcel= CreateObject("Excel.Application") Set oWb = oExcel.Workbooks.Open("E:其他新装电话表.xls") Set oSheet = oWb.Sheets("Sheet...

4、zabbix基本配置入门

Zabbix监控流程:Host group --> Hosts(向server端添加被监控主机) --> Application(在agent定义) --> Items(在applications内部定义) --> Triggers --> Events(触发器触发后产生事件) --> Actions(定义处理动作:...

SystemInfo获取设备系统参数

using UnityEngine; using System.Collections; using System.Collections.Generic; publicclassGameControllerScript:MonoBehaviour { //指定输出文本框 publicUnityEngine.UI.Text messageText; //存...

C#新DataColumn类Type生成的方法类型参数

DataColumn有的需要等级Type构造类型的参数,如以下: // // 摘要: // 使用指定列名称和数据类型初始化 System.Data.DataColumn 类的新实例。 // // 參数: // columnName:...

小目标 | DAX高级实践-Power BI与Excel联合应用

· 适用人群:数据分析专业人士,在数据分析方向需求发展人士 · 应用场景:数据汇报、数据可视化展现、数据建模分析 · 掌握难度:★★★★☆  本期讲师 DAX高级实践-Power BI与Excel联合应用   通过前序三篇文章的学习,大家已经了解到在DAX数据建模中如何搭建数据模型、如何设计数据模型中对于值的度量计算以及如何查询数据模型。   而在实际...