java EXCEL操作(包含多个sheet页)

直接上代码

工具类

package com.ruoyi.common.utils.poi;

import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.annotation.Excels;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.dto.ExcelExportDto;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.reflect.ReflectUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFDataValidation;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

/**
 * @BelongsPackage: com.ruoyi.common.utils.poi
 * @Author: zjt
 * @CreateTime: 2024-02-27  11:03
 * @Description: TODO
 * @Version: 1.0
 */

public class MultiExcellUtil {
    private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class);

    //表头
    public List<Object[]> fields;

    public static List<Object> importExcel(String sheetName, InputStream is, Class clazz) throws Exception {
        List<Object> list = new ArrayList<Object>();

        Workbook workbook = WorkbookFactory.create(is);
        Sheet sheet = workbook.getSheet(sheetName);
        if (sheet == null) {
            throw new IOException("文件sheet不存在");
        }
        int rows = sheet.getPhysicalNumberOfRows();
        if (rows > 0) {
            // 定义一个map用于存放excel列的序号和field.
            Map<String, Integer> cellMap = new HashMap<String, Integer>();
            Row heard = sheet.getRow(0);
            for (int i = 0; i < heard.getPhysicalNumberOfCells(); i++) {
                Cell cell = heard.getCell(i);
                if (StringUtils.isNotNull(cell)) {
                    String value = cell.getStringCellValue();
                    cellMap.put(value, i);
                } else {
                    cellMap.put(null, i);
                }
            }

            Field[] allFields = clazz.getDeclaredFields();
            // 定义一个Map用于存放列的序号和field
            Map<Integer, Field> fieldsMap = new HashMap<>();
            for (int col = 0; col < allFields.length; col++) {
                Field field = allFields[col];
                Excel attr = field.getAnnotation(Excel.class);
                if (attr != null) {
                    // 设置类的私有字段属性可访问.
                    field.setAccessible(true);
                    Integer column = cellMap.get(attr.name());
                    if (column != null) {
                        fieldsMap.put(column, field);
                    }
                }
            }
            for (int i = 1; i < rows; i++) {
                Row row = sheet.getRow(i);
                if (row == null) {
                    continue;
                }
                Object entity = null;
                for (Map.Entry<Integer, Field> entry : fieldsMap.entrySet()) {
                    Integer keyInt = entry.getKey();
                    if (StringUtils.isNull(keyInt)) {
                        System.out.println("--------------------");
                        continue;
                    }
                    Object val = getCellValue(row, entry.getKey());
                    // 如果不存在实例则新建.
                    entity = (entity == null ? clazz.newInstance() : entity);
                    // 从map中得到对应列的field.
                    Field field = fieldsMap.get(entry.getKey());
                    // 取得类型,并根据对象类型设置值.
                    Class<?> fieldType = field.getType();
                    if (String.class == fieldType) {
                        String s = Convert.toStr(val);
                        if (StringUtils.endsWith(s, ".0")) {
                            val = StringUtils.substringBefore(s, ".0");
                        } else {
                            String dateFormat = field.getAnnotation(Excel.class).dateFormat();
                            if (StringUtils.isNotEmpty(dateFormat)) {
                                val = DateUtils.parseDateToStr(dateFormat, (Date) val);
                            } else {
                                val = Convert.toStr(val);
                            }
                        }
                    } else if ((Integer.TYPE == fieldType || Integer.class == fieldType) && StringUtils.isNumeric(Convert.toStr(val))) {
                        val = Convert.toInt(val);
                    } else if (Long.TYPE == fieldType || Long.class == fieldType) {
                        val = Convert.toLong(val);
                    } else if (Double.TYPE == fieldType || Double.class == fieldType) {
                        val = Convert.toDouble(val);
                    } else if (Float.TYPE == fieldType || Float.class == fieldType) {
                        val = Convert.toFloat(val);
                    } else if (BigDecimal.class == fieldType) {
                        val = Convert.toBigDecimal(val);
                    } else if (Date.class == fieldType) {
                        if (val instanceof String) {
                            val = DateUtils.parseDate(val);
                        } else if (val instanceof Double) {
                            val = DateUtil.getJavaDate((Double) val);
                        }
                    } else if (Boolean.TYPE == fieldType || Boolean.class == fieldType) {
                        val = Convert.toBool(val, false);
                    }
                    if (StringUtils.isNotNull(fieldType)) {
                        Excel attr = field.getAnnotation(Excel.class);
                        String propertyName = field.getName();
                        if (StringUtils.isNotEmpty(attr.targetAttr())) {
                            propertyName = field.getName() + "." + attr.targetAttr();
                        } else if (StringUtils.isNotEmpty(attr.readConverterExp())) {
                            val = reverseByExp(Convert.toStr(val), attr.readConverterExp(), attr.separator());
                        } else if (StringUtils.isNotEmpty(attr.dictType())) {
                            val = reverseDictByExp(Convert.toStr(val), attr.dictType(), attr.separator());
                        }
                        ReflectUtils.invokeSetter(entity, propertyName, val);
                    }
                }
                list.add(entity);
            }
        }
        return list;
    }

    /**
     * 反向解析值字典值
     *
     * @param dictLabel 字典标签
     * @param dictType  字典类型
     * @param separator 分隔符
     * @return 字典值
     */
    public static String reverseDictByExp(String dictLabel, String dictType, String separator) {
        return DictUtils.getDictValue(dictType, dictLabel, separator);
    }

    /**
     * 反向解析值字典值
     *
     * @param dictValue 字典标签
     * @param dictType  字典类型
     * @param separator 分隔符
     * @return 字典值
     */
    public static String reverseDictValueByExp(String dictValue, String dictType, String separator) {
        return DictUtils.getDictLabel(dictType, dictValue, separator);
    }

    /**
     * 反向解析值 男=0,女=1,未知=2
     *
     * @param propertyValue 参数值
     * @param converterExp  翻译注解
     * @param separator     分隔符
     * @return 解析后值
     */
    public static String reverseByExp(String propertyValue, String converterExp, String separator) {
        StringBuilder propertyString = new StringBuilder();
        String[] convertSource = converterExp.split(",");
        for (String item : convertSource) {
            String[] itemArray = item.split("=");
            if (StringUtils.containsAny(separator, propertyValue)) {
                for (String value : propertyValue.split(separator)) {
                    if (itemArray[1].equals(value)) {
                        propertyString.append(itemArray[0] + separator);
                        break;
                    }
                }
            } else {
                if (itemArray[1].equals(propertyValue)) {
                    return itemArray[0];
                }
            }
        }
        return StringUtils.stripEnd(propertyString.toString(), separator);
    }

    /**
     * 获取单元格值
     *
     * @param row    获取的行
     * @param column 获取单元格列号
     * @return 单元格值
     */
    public static Object getCellValue(Row row, int column) {
        if (row == null) {
            return row;
        }
        Object val = "";
        try {
            Cell cell = row.getCell(column);
            if (StringUtils.isNotNull(cell)) {
                if (cell.getCellType() == CellType.NUMERIC || cell.getCellType() == CellType.FORMULA) {
                    val = cell.getNumericCellValue();
                    if (DateUtil.isCellDateFormatted(cell)) {
                        val = DateUtil.getJavaDate((Double) val); // POI Excel 日期格式转换
                    } else {
                        if ((Double) val % 1 != 0) {
                            val = new BigDecimal(val.toString());
                        } else {
                            val = new DecimalFormat("0").format(val);
                        }
                    }
                } else if (cell.getCellType() == CellType.STRING) {
                    val = cell.getStringCellValue();
                } else if (cell.getCellType() == CellType.BOOLEAN) {
                    val = cell.getBooleanCellValue();
                } else if (cell.getCellType() == CellType.ERROR) {
                    val = cell.getErrorCellValue();
                }

            }
        } catch (Exception e) {
            return val;
        }
        return val;
    }

    /**
     * Excel生成多个sheet页,但是注意单个sheet页的行数不能超过默认限制
     *
     * @param sheetNames
     * @param rowNameMap
     * @return
     */
    public static AjaxResult exportExcel(List<String> sheetNames, Map<String, Class> rowNameMap, String fileName) {
        Workbook workbook = new XSSFWorkbook();
        if (CollectionUtil.isNotEmpty(sheetNames)) {
            // 循环创建sheet页
            for (String sheetName : sheetNames) {
                Sheet sheet = workbook.createSheet(sheetName);
                Row row = sheet.createRow(0);
                //List<String> rowNameList = rowNameMap.get(sheetName);
                /*Class clazz = rowNameMap.get(sheetName);
                Field[] rowNameList = clazz.getDeclaredFields();
                if (rowNameList != null && rowNameList.length > 0) {
                    for (int i = 0; i < rowNameList.length; i++) {
                        Cell cell = row.createCell(i);
                        cell.setCellStyle(createStyles(workbook).get("header"));
                        cell.setCellValue(rowNameList[i].toString());
                        //Excel excel = (Excel) os[1];
                    }
                }*/
                List<Object[]> fields = createExcelField(rowNameMap.get(sheetName));
                int column = 0;
                for(Object[] os : fields) {
                    Excel excel = (Excel) os[1];
                    createCell(workbook, sheet, excel, row, column++);
                }
            }
        }

        try {
            FileOutputStream outputStream = new FileOutputStream(getAbsoluteFile(fileName));
            workbook.write(outputStream);
            outputStream.close();
            workbook.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return AjaxResult.success(fileName);
    }


    /**
     * 创建单元格
     */
    private static Cell createCell(Workbook workbook, Sheet sheet, Excel attr, Row row, int column) {
        // 创建列
        Cell cell = row.createCell(column);
        // 写入列信息
        cell.setCellValue(attr.name());
        setDataValidation(sheet, attr, row, column);
        cell.setCellStyle(createStyles(workbook).get("header"));
        return cell;
    }

    /**
     * 创建表格样式
     */
    public static void setDataValidation(Sheet sheet, Excel attr, Row row, int column) {
        if (attr.name().indexOf("注:") >= 0) {
            sheet.setColumnWidth(column, 6000);
        } else {
            // 设置列宽
            sheet.setColumnWidth(column, (int) ((attr.width() + 0.72) * 256));
        }
        // 如果设置了提示信息则鼠标放上去提示.
        if (StringUtils.isNotEmpty(attr.prompt())) {
            // 这里默认设了2-101列提示.
            setXSSFPrompt(sheet, "", attr.prompt(), 1, 100, column, column);
        }
        // 如果设置了combo属性则本列只能选择不能输入
        if (attr.combo().length > 0) {
            // 这里默认设了2-101列只能选择不能输入.
            setXSSFValidation(sheet, attr.combo(), 1, 100, column, column);
        }
    }
    /**
     * 设置 POI XSSFSheet 单元格提示
     *
     * @param sheet         表单
     * @param promptTitle   提示标题
     * @param promptContent 提示内容
     * @param firstRow      开始行
     * @param endRow        结束行
     * @param firstCol      开始列
     * @param endCol        结束列
     */
    public static void setXSSFPrompt(Sheet sheet, String promptTitle, String promptContent, int firstRow, int endRow,
                              int firstCol, int endCol) {
        DataValidationHelper helper = sheet.getDataValidationHelper();
        DataValidationConstraint constraint = helper.createCustomConstraint("DD1");
        CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
        DataValidation dataValidation = helper.createValidation(constraint, regions);
        dataValidation.createPromptBox(promptTitle, promptContent);
        dataValidation.setShowPromptBox(true);
        sheet.addValidationData(dataValidation);
    }

    /**
     * 设置某些列的值只能输入预制的数据,显示下拉框.
     *
     * @param sheet    要设置的sheet.
     * @param textlist 下拉框显示的内容
     * @param firstRow 开始行
     * @param endRow   结束行
     * @param firstCol 开始列
     * @param endCol   结束列
     * @return 设置好的sheet.
     */
    public static void setXSSFValidation(Sheet sheet, String[] textlist, int firstRow, int endRow, int firstCol, int endCol) {
        DataValidationHelper helper = sheet.getDataValidationHelper();
        // 加载下拉列表内容
        DataValidationConstraint constraint = helper.createExplicitListConstraint(textlist);
        // 设置数据有效性加载在哪个单元格上,四个参数分别是:起始行、终止行、起始列、终止列
        CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
        // 数据有效性对象
        DataValidation dataValidation = helper.createValidation(constraint, regions);
        // 处理Excel兼容性问题
        if (dataValidation instanceof XSSFDataValidation) {
            dataValidation.setSuppressDropDownArrow(true);
            dataValidation.setShowErrorBox(true);
        } else {
            dataValidation.setSuppressDropDownArrow(false);
        }

        sheet.addValidationData(dataValidation);
    }


    private static List<Object[]> createExcelField(Class clazz) {
        List<Object[]> fieldList = new ArrayList<>();
        List<Field> tempFields = new ArrayList<>();
        tempFields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields()));
        tempFields.addAll(Arrays.asList(clazz.getDeclaredFields()));
        for (Field field : tempFields) {
            // 单注解
            if (field.isAnnotationPresent(Excel.class)) {
                fieldList.add(new Object[]{field, field.getAnnotation(Excel.class)});
            }

            // 多注解
            if (field.isAnnotationPresent(Excels.class)) {
                Excels attrs = field.getAnnotation(Excels.class);
                Excel[] excels = attrs.value();
                for (Excel excel : excels) {
                    fieldList.add(new Object[]{field, excel});
                }
            }
        }
        return fieldList;
    }

    public static String getAbsoluteFile(String fileName) {
        String downloadPath = RuoYiConfig.getDownloadPath() + fileName;
        File desc = new File(downloadPath);
        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }
        return downloadPath;
    }

    private static Map<String, CellStyle> createStyles(Workbook wb) {
        // 写入各条记录,每条记录对应excel表中的一行
        Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
        CellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setBorderRight(BorderStyle.THIN);
        style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setBorderLeft(BorderStyle.THIN);
        style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setBorderTop(BorderStyle.THIN);
        style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setBorderBottom(BorderStyle.THIN);
        style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        Font dataFont = wb.createFont();
        dataFont.setFontName("Arial");
        dataFont.setFontHeightInPoints((short) 10);
        style.setFont(dataFont);
        styles.put("data", style);

        style = wb.createCellStyle();
        style.cloneStyleFrom(styles.get("data"));
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        Font headerFont = wb.createFont();
        headerFont.setFontName("Arial");
        headerFont.setFontHeightInPoints((short) 10);
        headerFont.setBold(true);
        headerFont.setColor(IndexedColors.WHITE.getIndex());
        style.setFont(headerFont);
        styles.put("header", style);

        style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        Font totalFont = wb.createFont();
        totalFont.setFontName("Arial");
        totalFont.setFontHeightInPoints((short) 10);
        style.setFont(totalFont);
        styles.put("total", style);

        style = wb.createCellStyle();
        style.cloneStyleFrom(styles.get("data"));
        style.setAlignment(HorizontalAlignment.LEFT);
        styles.put("data1", style);

        style = wb.createCellStyle();
        style.cloneStyleFrom(styles.get("data"));
        style.setAlignment(HorizontalAlignment.CENTER);
        styles.put("data2", style);

        style = wb.createCellStyle();
        style.cloneStyleFrom(styles.get("data"));
        style.setAlignment(HorizontalAlignment.RIGHT);
        styles.put("data3", style);

        return styles;
    }

    /**
     * 多sheet页数据导出
     * @param data 导出信息
     * @param fileName 文件名
     * @return
     */
    public static AjaxResult manyDataExportExcel(List<ExcelExportDto> data, String fileName){
        Workbook workbook = new XSSFWorkbook();

        if (CollectionUtil.isNotEmpty(data)) {

            // 循环创建sheet页
            for (ExcelExportDto excelExportDto : data) {

                //无数据是跳出循环
                if(excelExportDto.getData()==null){
                    continue;
                }

                Sheet sheet = workbook.createSheet(excelExportDto.getSheetName());
                Row row = sheet.createRow(0);
                List<Object[]> fields = createExcelField(excelExportDto.getClazz());
                int column = 0;
                for(Object[] os : fields) {
                    Excel excel = (Excel) os[1];
                    createCell(workbook, sheet, excel, row, column++);
                }

                //需导入数据
                List dataList=excelExportDto.getData();

                //循环导入数据
                for (int index=0;index<dataList.size();index++) {

                    //根据数据创建行
                    Row currentRow=sheet.createRow(index+1);

                    for (int i=0;i<fields.size();i++){
                        // 创建列
                        Cell cell = currentRow.createCell(i);

                        try {
                            //获取类字段下的字段值
                            Field field = (Field) fields.get(i)[0];
                            Excel excel = (Excel) fields.get(i)[1];
                            Field valueField=dataList.get(index).getClass().getDeclaredField(field.getName());
                            //将字段访问设为公有
                            valueField.setAccessible(true);
                            Object value=valueField.get(dataList.get(index));

                            //判断当前字段是否时间类型
                            if(Date.class.isAssignableFrom(field.getType())){
                                String dateFormat = field.getAnnotation(Excel.class).dateFormat();
                                //字段为时间类型并且数据不为空时转换数据类型
                                if (StringUtils.isNotEmpty(dateFormat) && !Objects.isNull(value)) {
                                    value = DateUtils.parseDateToStr(dateFormat, (Date) value);
                                } else {
                                    value = Convert.toStr(value);
                                }
                            }

                            //当前字段是否有dictType字段注解,有则转换数据
                            if(StringUtils.isNotEmpty(excel.dictType())){
                                String reverseValue=reverseDictValueByExp(Convert.toStr(value), excel.dictType(), excel.separator());
                                if(StringUtils.isNotEmpty(reverseValue)){
                                    value=reverseValue;
                                }
                            }

                            // 写入列信息
                            cell.setCellValue(value==null?"":value.toString());
                            cell.setCellStyle(createStyles(workbook).get("data"));
                            setDataValidation(sheet, excel, currentRow, i);
                        }catch (Exception e){
                            throw new RuntimeException(e);
                        }
                    }
                }
                //如果设了需合并列,则开始合并单元格
                if(excelExportDto.getCells().length>0&&excelExportDto.getCells()!=null){
                    addCellRange(sheet,excelExportDto.getCells());
                }
            }
        }

        try {
            fileName=UUID.randomUUID().toString() + "_" + fileName + ".xlsx";
            FileOutputStream outputStream = new FileOutputStream(getAbsoluteFile(fileName));
            workbook.write(outputStream);
            outputStream.close();
            workbook.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return AjaxResult.success(fileName);
    }

    /**
     * 设置单元格合并
     * @param sheet sheet
     * @param index 需合并的下标数组
     */
    private static void addCellRange(Sheet sheet, int[] index){
        //核对指定列
        for (Integer integer : index) {

            //开始行
            int startIndex=0;
            //结束行
            int endInex=0;
            //数据
            String value="";

            //循环excel数据合并单元格
            for (int i =0;i<sheet.getLastRowNum()+1;i++){

                //获取当前单元格牛内容
                String currentValue=sheet.getRow(i).getCell(integer).getStringCellValue();
                //跳过表头并开始赋值
                if(i==0){
                    value=currentValue;
                    continue;
                }

                //单元格内容不相同并且所在行不一样时合并单元格
                if(!currentValue.equals(value)){
                    if(startIndex!=endInex){
                        CellRangeAddress cellAddresses=new CellRangeAddress(startIndex,endInex,integer,integer);
                        sheet.addMergedRegion(cellAddresses);
                    }
                    value=currentValue;
                    startIndex=i;
                    endInex=i;
                }else{
                    endInex=i;
                }

                //核对最后一行内容相同则合并
                if(sheet.getLastRowNum()==i){
                    if(value.equals(currentValue) && i!=startIndex){
                        CellRangeAddress cellAddresses=new CellRangeAddress(startIndex,sheet.getLastRowNum(),integer,integer);
                        sheet.addMergedRegion(cellAddresses);
                    }
                }
            }
        }
    }

    /**
     * 创建并填入单元格数据
     */
    private static Cell createCell(Workbook workbook, Sheet sheet, Excel attr, Row row, int column,Field field) {
        // 创建列
        Cell cell = row.createCell(column);
        // 写入列信息
        cell.setCellValue(attr.name());
        setDataValidation(sheet, attr, row, column);
        cell.setCellStyle(createStyles(workbook).get("header"));
        return cell;
    }
}

测试案例

package com.ruoyi.common.utils.poi;

import org.apache.poi.ss.usermodel.Cell;
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.XSSFWorkbook;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/**
 * @BelongsPackage: com.ruoyi.common.utils.poi
 * @Author: zjt
 * @CreateTime: 2024-02-27  10:30
 * @Description: TODO
 * @Version: 1.0
 */

public class TestDemo {
    public static void main(String[] args) {
        Workbook workbook = new XSSFWorkbook();

        Sheet sheet1 = workbook.createSheet("竞赛组织情况");
        Sheet sheet2 = workbook.createSheet("竞赛决赛情况");

        // 写入数据到sheet1
        Row row1 = sheet1.createRow(0);
        Cell cell1 = row1.createCell(0);
        cell1.setCellValue("hello");
        Cell cell11 = row1.createCell(1);
        cell11.setCellValue("word");

        Row row2 = sheet2.createRow(0);
        Cell cell2 = row2.createCell(0);
        cell2.setCellValue("hello");
        try {
            FileOutputStream outputStream = new FileOutputStream("D:\\test.xlsx");
            workbook.write(outputStream);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

看不懂的私聊

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: 好的,这是一个关于Java操作Excel的问题,我可以回答。要在Java中导出多个SheetExcel,你需要使用Apache POI这个Java库。以下是一个示例代码,可以在Java中导出包含多个SheetExcel文件: ``` import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelExportExample { public static void main(String[] args) { try (Workbook workbook = new XSSFWorkbook()) { // 创建Sheet1 Sheet sheet1 = workbook.createSheet("Sheet1"); // 创建Sheet2 Sheet sheet2 = workbook.createSheet("Sheet2"); // 写入Sheet1数据 Cell cell11 = sheet1.createRow(0).createCell(0); cell11.setCellValue("Sheet1-Row1-Cell1"); // 写入Sheet2数据 Cell cell21 = sheet2.createRow(0).createCell(0); cell21.setCellValue("Sheet2-Row1-Cell1"); // 导出Excel文件 try (FileOutputStream outputStream = new FileOutputStream("example.xlsx")) { workbook.write(outputStream); } System.out.println("Excel导出成功!"); } catch (IOException e) { e.printStackTrace(); } } } ``` 在这个示例代码中,我们使用XSSFWorkbook创建了一个新的Excel文件。然后我们创建了两个Sheet,分别是"Sheet1"和"Sheet2"。接着我们在每个Sheet创建了一个单元格,并写入了一些数据。最后我们使用FileOutputStream将Excel文件写入磁盘中。 希望这个示例能够帮助到你! ### 回答2: 在Java中,我们可以使用Apache POI库来导出多个sheetExcel文件。下面是一个简单的示例代码: ```java import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileOutputStream; import java.io.IOException; public class ExcelExporter { public static void main(String[] args) { try (Workbook workbook = new XSSFWorkbook()) { // 创建第一个sheet Sheet sheet1 = workbook.createSheet("Sheet1"); // 创建第一个sheet的第一行,并设置数据 Row row1 = sheet1.createRow(0); Cell cell1 = row1.createCell(0); cell1.setCellValue("Sheet1中的第一行,第一列的数据"); // 创建第二个sheet Sheet sheet2 = workbook.createSheet("Sheet2"); // 创建第二个sheet的第一行,并设置数据 Row row2 = sheet2.createRow(0); Cell cell2 = row2.createCell(0); cell2.setCellValue("Sheet2中的第一行,第一列的数据"); // 保存Excel文件 try (FileOutputStream outputStream = new FileOutputStream("多个sheetExcel文件.xlsx")) { workbook.write(outputStream); } System.out.println("Excel文件导出成功"); } catch (IOException e) { e.printStackTrace(); } } } ``` 以上代码使用了Apache POI库的`XSSFWorkbook`类来创建一个新的Excel文件。我们使用`createSheet`方法来创建多个sheet,并使用`createRow`和`createCell`方法来创建行和单元格,并设置相应的数据。最后,使用`FileOutputStream`将Workbook对象写入文件中。 以上代码只是一个简单的示例,您可以根据自己的需求来设置更多的行和单元格,并可以为每个sheet设置不同的数据。希望对您有帮助! ### 回答3: 在Java中,可以使用Apache POI库来导出Excel多个sheet。首先,你需要在你的项目中包含Apache POI库的依赖。 接下来,你可以创建一个Workbook对象,该对象代表整个Excel文档。使用Workbook对象的createSheet方法可以创建一个新的sheet。你可以使用sheet的setName方法来设置sheet的名称。 然后,你可以使用Row和Cell对象来创建和填充sheet中的行和单元格。使用Row对象的createCell方法可以创建一个新的单元格,然后使用Cell对象的setCellValue方法来设置单元格的值。 最后,将生成的数据写入Excel文件中。你可以使用Workbook对象的write方法将Workbook对象中的数据写入文件中。 以下是一个简单的示例代码来导出多个sheetExcel文件: ```java import org.apache.poi.ss.usermodel.*; import java.io.FileOutputStream; import java.io.IOException; public class ExportExcelMultiSheet { public static void main(String[] args) { Workbook workbook = new XSSFWorkbook(); createSheet(workbook, "Sheet1"); createSheet(workbook, "Sheet2"); createSheet(workbook, "Sheet3"); try (FileOutputStream fileOut = new FileOutputStream("output.xlsx")) { workbook.write(fileOut); } catch (IOException e) { e.printStackTrace(); } System.out.println("Excel文件导出成功!"); } private static void createSheet(Workbook workbook, String sheetName) { Sheet sheet = workbook.createSheet(sheetName); Row headerRow = sheet.createRow(0); Cell headerCell = headerRow.createCell(0); headerCell.setCellValue(sheetName + " Header"); Row dataRow = sheet.createRow(1); Cell dataCell = dataRow.createCell(0); dataCell.setCellValue(sheetName + " Data"); } } ``` 上述代码创建了一个名为"output.xlsx"的Excel文件,其中包含了三个sheet,分别为"Sheet1"、"Sheet2"和"Sheet3"。每个sheet中都包含了一个标题行和一个数据行。 希望上述信息能够帮助到你!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小城忧伤

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

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

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

打赏作者

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

抵扣说明:

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

余额充值