java excel导入导出工具类(基于poi类库),chatgpt提供的 超简单带使用方法

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

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
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.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
* excel文件读写工具类
*/
public class ExcelUtils {

    /**
     * 创建工作簿
     */
    public static Workbook createWorkbook() {
        return new XSSFWorkbook();
    }
    
    /**
     * 创建表格样式
     */
    public static CellStyle createStyleForHeader(Workbook workbook) {
        XSSFCellStyle style = (XSSFCellStyle) workbook.createCellStyle();
        style.setFillForegroundColor(IndexedColors.AQUA.getIndex());
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
        style.setBorderBottom(CellStyle.BORDER_THIN);
        style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderLeft(CellStyle.BORDER_THIN);
        style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderRight(CellStyle.BORDER_THIN);
        style.setRightBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderTop(CellStyle.BORDER_THIN);
        style.setTopBorderColor(IndexedColors.BLACK.getIndex());

        XSSFFont font=(XSSFFont) workbook.createFont();
        font.setFontHeightInPoints((short)12);
        font.setBoldweight(Font.BOLDWEIGHT_BOLD);
        font.setFontName("华文隶书");
        style.setFont(font);
        return style;
    }
    
    /**
     * 新建工作表
     */
    public static Sheet createSheet(Workbook workbook, String sheetName, int sheetNum) {
        return workbook.createSheet(sheetName + sheetNum);
    }
    
    /**
     * 导出excel文件
     */
    public static void exportExcel(List<String[]> dataList, String[] headers, File file) throws IOException {
        Workbook workbook = createWorkbook();
        Sheet sheet = createSheet(workbook, "Sheet", 1);
        //设置表头样式
        CellStyle style = createStyleForHeader(workbook);
        Row rowHeader = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            Cell cellHeader = rowHeader.createCell(i);
            sheet.setColumnWidth(i, 20 * 256);//设置列宽
            cellHeader.setCellValue(headers[i]);
            cellHeader.setCellStyle(style);
        }
        //填充数据
        for (int i = 0; i < dataList.size(); i++) {
            String[] data = dataList.get(i);
            Row row = sheet.createRow(i + 1);
            for (int j = 0; j < headers.length; j++) {
                Cell cell = row.createCell(j);
                cell.setCellValue(data[j]);
                sheet.setColumnWidth(j, 20 * 256);//设置列宽
            }
        }
        // 输出文件
        FileOutputStream fos = new FileOutputStream(file);
        workbook.write(fos);
        fos.close();
    }
    
    /**
     * 导入excel文件
     */
    public static List<String[]> importExcel(File file) throws IOException {
        List<String[]> dataList = new ArrayList<String[]>();
        FileInputStream fis = new FileInputStream(file);
        Workbook workbook = new XSSFWorkbook(fis);
        Sheet sheet = workbook.getSheetAt(0);
        int firstRowIndex = sheet.getFirstRowNum();
        int lastRowIndex = sheet.getLastRowNum();
        //遍历每一行
        for (int rowIndex = firstRowIndex + 1; rowIndex <= lastRowIndex; rowIndex++) {
            Row currentRow = sheet.getRow(rowIndex);
            int firstColumnIndex = currentRow.getFirstCellNum();
            int lastColumnIndex = currentRow.getLastCellNum();
            String[] data = new String[lastColumnIndex];
            //遍历每一列
            for (int columnIndex = firstColumnIndex; columnIndex < lastColumnIndex; columnIndex++) {
                Cell currentCell = currentRow.getCell(columnIndex);
                String cellValue = "";
                if (currentCell.getCellType() == Cell.CELL_TYPE_STRING) { 
                    cellValue = currentCell.getStringCellValue();
                } else if (currentCell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
                    cellValue = String.valueOf(currentCell.getNumericCellValue());
                }
                data[columnIndex] = cellValue;
            }
            dataList.add(data);
        }
        fis.close();
        return dataList;
    }
}

使用该类的时候,你需要这样操作:

public class TestExcel {
    public static void main(String[] args) throws Exception {
        String[] headers = {"姓名", "年龄", "性别", "爱好"};
        String[][] data = {
                {"小红", "18", "女", "游泳"},
                {"小明", "20", "男", "画画"},
                {"小丽", "22", "女", "瑜伽"}
        };
        List<String[]> dataList = new ArrayList<String[]>();
        for (int i = 0; i < data.length; i++) {
            dataList.add(data[i]);
        }
        File file = new File("D:/test.xlsx");
        ExcelUtils.exportExcel(dataList, headers, file);
        List<String[]> result = ExcelUtils.importExcel(file);
        for (String[] strings : result) {
            System.out.println(Arrays.toString(strings));
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

北凉军

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值