excel导入导出

引入jar包

<!--Excel导入 poi poi-ooxml-->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>

导入

import org.apache.poi.ss.usermodel.*;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 导入excel
 *
 */
public class ExcelImport {

    public static void main(String[] args) {
        ExcelImport excelImport = new ExcelImport();
        excelImport.readExcel(new File("C:\\Users\\admin\\Desktop\\w_import.xlsx"));
    }

    public void readExcel(File file) {
        int columns = 3;
        try {
            Workbook sheets = WorkbookFactory.create(file);
//            Workbook sheets = XSSFWorkbookFactory.create(new File("C:\\Users\\admin\\Desktop\\white_import.xlsx"));
//            Workbook sheets = HSSFWorkbookFactory.create(new File("C:\\Users\\admin\\Desktop\\white_import.xlsx"));

            Sheet sheet = sheets.getSheetAt(0);

            int lastRowNum = sheet.getLastRowNum();
            System.out.println("总行数:" + lastRowNum);

            Row headRow = sheet.getRow(0);
            if (headRow.getPhysicalNumberOfCells() != columns) {
                System.out.println("列数不对");
                return;
            }
            for (int i = 0; i < columns; i++) {
                System.out.print(headRow.getCell(i));
                System.out.print(" | ");
            }
            for (int i = 1; i <= lastRowNum; i++) {
                System.out.println();
                Row row = sheet.getRow(i);
                for (int j = 0; j < columns; j++) {
                    Cell cell = row.getCell(j);
                    System.out.print(parseCell(cell));
                    System.out.print(" | ");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private Object parseCell(Cell cell) {
        Object cellValue = "";
        if (cell != null) {
            CellType cellType = cell.getCellType();
            switch (cellType) {
                case NUMERIC:
                    if (DateUtil.isCellDateFormatted(cell)) {
                        Date dateCellValue = cell.getDateCellValue();
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        cellValue = format.format(dateCellValue);
                    } else {
                        DataFormatter dataFormatter = new DataFormatter();
                        cellValue = dataFormatter.formatCellValue(cell);
                    }
                    break;
                case STRING:
                    cellValue = cell.getStringCellValue();
                    break;
                case BOOLEAN:
                    cellValue = cell.getBooleanCellValue();
                    break;
                case FORMULA:
                    cellValue = cell.getCellFormula();
                    break;
                case BLANK:
                case ERROR:
                    cellValue = "";
                    break;
                default:
                    break;
            }
        }
        return cellValue;
    }

}

导出

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author admin
 */
public class ExcelExport {

    public static void main(String[] args) {
        ExcelExport excelExport = new ExcelExport();
        try {
            excelExport.export(new FileOutputStream(new File("C:\\Users\\admin\\Desktop\\test_import.xlsx")));
            System.out.println("导出成功");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void export(OutputStream outputStream) {

        Workbook workbook = createWorkBook();

        try {
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private Workbook createWorkBook() {
        Workbook workbook = XSSFWorkbookFactory.createWorkbook();
        Sheet sheet = workbook.createSheet("sheet1");

        CellStyle cellStyle = setCellStyle(workbook);
        CellStyle headStyle = setHeadCellStyle(workbook);

        createRowHead(sheet, headStyle);
        createRows(sheet, cellStyle);
        return workbook;
    }

    private Font setFont(Workbook workbook) {
        Font font = workbook.createFont();
        font.setFontHeightInPoints((short) 12);
        font.setBold(true);
        font.setFontName("宋体");
        return font;
    }

    private CellStyle setHeadCellStyle(Workbook workbook) {
        Font font = setFont(workbook);
        CellStyle headStyle = workbook.createCellStyle();
        headStyle.setFont(font);
        headStyle.setAlignment(HorizontalAlignment.CENTER);
        headStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        headStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
        return headStyle;
    }

    private CellStyle setCellStyle(Workbook workbook) {
        Font font = setFont(workbook);
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFont(font);
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        return cellStyle;
    }

    private void createRows(Sheet sheet, CellStyle cellStyle) {
        for (int i = 1; i <= 5; i++) {
            Row row = sheet.createRow(i);
            for (int j = 0; j < 2; j++) {
                Cell cell = row.createCell(j);
                cell.setCellStyle(cellStyle);
                cell.setCellValue("test_" + i + "_" + j);
            }
            sheet.autoSizeColumn(i);
        }
    }

    private void createRowHead(Sheet sheet, CellStyle cellStyle) {
        Row row = sheet.createRow(0);
        Cell cell = row.createCell(0);
        cell.setCellStyle(cellStyle);
        cell.setCellValue("测试名称");
        Cell cell1 = row.createCell(1);
        cell1.setCellStyle(cellStyle);
        cell1.setCellValue("测试");

        sheet.autoSizeColumn(0);
    }

    public void browserExport(HttpServletRequest request, HttpServletResponse response) {
        Workbook workbook = createWorkBook();

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = format.format(new Date());
        String filename = "test_export_" + date + ".xlsx";
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            response.setHeader("Content-Disposition", "attachment; filename=".concat(filename));
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
            bufferedOutputStream.flush();

            workbook.write(bufferedOutputStream);
            outputStream.close();
            bufferedOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Excel是一种常用的电子表格软件,可以用于数据的存储和处理。在Java中,我们可以使用POI和JXL两种方式来实现Excel导入导出。其中,POI支持Excel 2007及以上版本,而JXL支持比较低版本的Excel,如Excel 95、97、2000、2003。下面是两种方式的简单实例: 1.使用POI实现Excel导入导出 ```java // 导入Excel Workbook workbook = WorkbookFactory.create(new FileInputStream("test.xlsx")); Sheet sheet = workbook.getSheetAt(0); for (Row row : sheet) { for (Cell cell : row) { System.out.print(cell.getStringCellValue() + "\t"); } System.out.println(); } // 导出Excel Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet("Sheet1"); Row row = sheet.createRow(0); Cell cell = row.createCell(0); cell.setCellValue("Hello World!"); FileOutputStream outputStream = new FileOutputStream("test.xlsx"); workbook.write(outputStream); outputStream.close(); ``` 2.使用JXL实现Excel导入导出 ```java // 导入Excel Workbook workbook = Workbook.getWorkbook(new File("test.xls")); Sheet sheet = workbook.getSheet(0); for (int i = 0; i < sheet.getRows(); i++) { for (int j = 0; j < sheet.getColumns(); j++) { Cell cell = sheet.getCell(j, i); System.out.print(cell.getContents() + "\t"); } System.out.println(); } // 导出Excel WritableWorkbook workbook = Workbook.createWorkbook(new File("test.xls")); WritableSheet sheet = workbook.createSheet("Sheet1", 0); Label label = new Label(0, 0, "Hello World!"); sheet.addCell(label); workbook.write(); workbook.close(); ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值