Как импортировать java в excel

импорт и экспорт java в Excel

    • java импорт данных Excel
      • Уровень контроллера
      • Уровень ServiceImpl
    • экспорт Java в Excel
      • Уровень контроллера
      • Уровень ServiceImpl
      • Инструмент экспорта в Excel

java импорт данных Excel

Уровень контроллера

 @PostMapping(value = "/importInfo")
    public Map<String, Object> importInfo(@CookieValue(value = "token_back") String token, @RequestParam(value = "file") MultipartFile file, @RequestParam(value = "code") String code) {
        TbSysUser user = RedisUtil.tokenToUser(token);
        // Код оператора
        String operatorId = user.getLoginCode();
        // Имя оператора
        String operatorName = user.getName();
        // Время операции
        Timestamp operateDateTime = new Timestamp(new Date().getTime());
        Map<String, Object> map = new HashMap<>();
        try {
            String message = memberImportService.exportInfo(file, code, operatorId, operatorName, operateDateTime);
            map.put("success", true);
            map.put("message", message);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            map.put("success", false);
            map.put("message", «Ошибка импорта»);
            return map;
        }
    }

Уровень ServiceImpl

@Override
    public String exportInfo(MultipartFile file, String code, String operatorId, String operatorName, Timestamp operateDateTime) throws Exception {
        String message = «Импорт выполнен успешно»;
        String listTypeID = code.split("\*")[0].toString().trim();
        String listTypeName = code.split("\*")[1].toString().trim();
        Workbook workbook = null;
        String fileName = file.getOriginalFilename();
        ExcelUtil eu = new ExcelUtil();
        // Оценка типа файла
        if (fileName.endsWith("xls")) {
            try {
                workbook = new HSSFWorkbook(file.getInputStream());// Версия 2003 г.
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (fileName.endsWith("xlsx")) {
            try {
                workbook = new XSSFWorkbook(file.getInputStream());// Версия 2007 г.
            } catch (IOException e) {
                e.printStackTrace();
            }

        } else {
            try {
                throw new Exception(«Файл не является файлом Excel»);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Sheet sheet = workbook.getSheet("sheet1");
        int rows = sheet.getLastRowNum();
        if (rows == 0) {
            try {
                throw new Exception("Данные пусты, введите данные еще раз");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // Получаем первую форму в документе Excel
        Sheet sht0 = workbook.getSheetAt(0);
        Row ro = sht0.getRow(1);
        boolean flag = false;
        Cell cell = ro.getCell(4);
        String cellName = null;
        if (cell != null) {
            cellName = cell.getStringCellValue();
        }
        if (cellName != null && cellName.trim().length() > 0) {
            if (!"Замечания".equals(cellName)) {
                message = «Ошибка импорта шаблона, повторите импорт»;
                return message;
            }
            flag = true;
        } else {
            cell = ro.getCell(2);
            if (cell != null) {
                cellName = cell.getStringCellValue();
            }

            if (cellName == null || (cellName.trim().length() > 0 && !"Замечания".equals(cellName))) {
                message = «Ошибка импорта шаблона, повторите импорт»;
                return message;
            }
        }
        // Перебираем каждую строку на листе
        for (Row r : sht0) {
            // Если номер текущей строки (начиная с 0) не достигает 2 (третья строка), перезапускаем
            int rnum = r.getRowNum() + 1;
            if (r.getRowNum() < 2) {
                continue;
            }
            // Создаем класс сущности
            TbMemberImport info = new TbMemberImport();
            // Извлекаем данные первой ячейки текущей строки и инкапсулируем их в атрибут stuName информационного объекта
            // лет
            info.setYear(eu.getCellValue(r.getCell(0)));
            // Имя трейдера
            info.setFullName(eu.getCellValue(r.getCell(1)));
            if (flag) {
                // Разнообразие
                String memo = eu.getCellValue(r.getCell(4));
                if (memo != null && memo.trim().length() > 0) {
                    // Замечания
                    info.setMemo(eu.getCellValue(r.getCell(4)));
                } else {
                    message = " " + rnum + "Строка примечания не может быть пустой!";
                    return message;
                }
                info.setVarietyName(eu.getCellValue(r.getCell(2)));
                // Ежедневная производительность обработки
                info.setDayProcess(new java.math.BigDecimal(eu.getCellValue(r.getCell(3))));
            } else {
                // Замечания
                String memo = eu.getCellValue(r.getCell(2));
                if (memo != null && memo.trim().length() > 0) {
                    // Замечания
                    info.setMemo(eu.getCellValue(r.getCell(4)));
                } else {
                    message = " " + rnum + "Строка примечания не может быть пустой!";
                    return message;
                }
            }
            info.setMemberId("");
            info.setVarietyId("");
            info.setOperatorId(operatorId);
            info.setOperatorName(operatorName);
            info.setOperateDateTime(operateDateTime);
            info.setListTypeId(listTypeID);
            info.setListTypeName(listTypeName);
            info.setStatus("WX");
            tbMemberImportMapper.insert(info);
            for (int i = 1; i <= rows + 1; i++) {
                Row row = sheet.getRow(i);
                if (row != null) {

                }
            }
        }
        return message;
    }

экспорт Java в Excel

Уровень контроллера

 @PostMapping("/export")
    public void exportContractList(HttpServletRequest request, HttpServletResponse response, @CookieValue(value="token_back")String token){
        try {
            List<TbContractExport> contractList = contractMngService.contractExportData(request,RedisUtil.tokenToUser(token));

            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+«Информация о контракте», "UTF-8") + ".xls");
            ExcelUtil<TbContractExport> excelUtil = new ExcelUtil<>();
            excelUtil.exportExcel2003(«Информация о контракте», exportColumns, contractList, response.getOutputStream(), "yyyy-MM-dd");
        }catch (Exception e){
            // Временно не обрабатываются, отправляем сообщения в rabbitMQ для записи в таблицу журнала позже
        }
    }
 @GetMapping(value = "/exportExcel")
    public void exportExcel(
            HttpServletResponse response,
            @RequestParam(value = "data") String data
    ) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(data);
            String buyStatus = jsonObject.getString("buyStaus");
            String fullName = jsonObject.getString("fullName");
            String listTypeId = jsonObject.getString("listTypeId");
            String marketId = jsonObject.getString("marketId");
            String marketIdZc = jsonObject.getString("marketIdZc");
            String memberId = jsonObject.getString("memberId");
            String varietyId = jsonObject.getString("varietyId");
            String status = jsonObject.getString("status");
            String specialNo = jsonObject.getString("specialNo");
//            OutputStream os = response.getOutputStream();
            memberBuyNumLimitService.exportExcel(response, buyStatus, fullName, listTypeId, marketId, marketIdZc, memberId, varietyId, status, specialNo);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Уровень ServiceImpl

 @Override
    public void exportExcel(HttpServletResponse response, String buyStatus, String fullName, String listTypeId, String marketId, String marketIdZc, String memberId, String varietyId, String status, String specialNo) throws Exception {
//        List<TbMemberBuyNumLimitView> list = tbMemberBuyNumLimitMapper.getMemberBuyInfo(buyStatus, fullName, listTypeId, marketId, marketIdZc, memberId, varietyId, status, specialNo);
        List<TbMemberBuyNumLimitView> list = null;
        if (marketIdZc == null || marketIdZc.trim().length() <= 0) {
            list = tbMemberBuyNumLimitMapper.getMemberBuyInfo(buyStatus, fullName, listTypeId, marketId, memberId, varietyId, status, specialNo);
        } else {
            list = tbMemberBuyNumLimitMapper.getMemberBuyInfoZc(buyStatus, fullName, listTypeId, marketId, marketIdZc, memberId, varietyId, status, specialNo);
        }

        ExcelUtil excelUtil = new ExcelUtil();
        String[] headers = {"Список", "Код", "название", "рынок", "Специальный", "Разнообразие", «Производительность», «Объем одной транзакции», «1 торгуемый объем», «2Торговый объем», "Обязательство", "торговый статус", «Лимит торгового объема»};
        List<Object> rows = new ArrayList<>();
        for (TbMemberBuyNumLimitView tb : list) {
            List<String> row = new ArrayList<>();
            String numConvertName = tb.getNumConvertName();
            row.add(tb.getListTypeName());
            row.add(tb.getMemberId());
            row.add(tb.getFullName());
            row.add(tb.getMarketName());
            row.add(tb.getSpecialName());
            row.add(tb.getVarietyName());
            if(tb.getDayProcess() == null){
                row.add("нет данных");
            }else{
                row.add(tb.getDayProcess().toString() + numConvertName);
            }
            if(tb.getSingleBuy() == null){
                row.add("нет данных");
            }else {
                row.add(tb.getSingleBuy().toString() + numConvertName);
            }
            if(tb.getMonthBuy() == null){
                row.add("нет данных");
            }else {
                row.add(tb.getMonthBuy().toString() + numConvertName);
            }
            if(tb.getTotalBuy() == null){
                row.add("нет данных");
            }else {
                row.add(tb.getTotalBuy().toString() + numConvertName);
            }
            String commitment = tb.getCommitment();
            if ("Y".equals(commitment)) {
                row.add("Да");
            } else {
                row.add("нет");
            }
            String bs = tb.getBuyStatus();
            if ("Y".equals(bs)) {
                row.add("Торгуемый");
            } else {
                row.add(«Прекратить торговать»);
            }
            String st = tb.getStatus();
            if ("Y".equals(st)) {
                row.add("предел");
            } else {
                row.add("не ограничен");
            }
            rows.add(row);
        }
        String time = DateUtils.dateToStringByTemplate(new Date(), "yyyyMMddHHmmss");
        String fileName = time + «***** List.xls»;
        excelUtil.listToExcel(headers, rows, fileName, «ХХ Список», response);
    }

Инструмент экспорта в Excel


import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import javax.servlet.http.HttpServletResponse;
import java.awt.Color;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 
   * @description инструменты импорта и экспорта Excel
 * @date 2018-8-2
 */
public class ExcelUtil<T> {
    // До версии 2007 поддерживает 1048576 строк
    public final static String EXCEL_FILE_2007 = "2007";
    // Версия 2003 поддерживает до 65536 строк
    public final static String EXCEL_FILE_2003 = "2003";

    /**
           * Описание функции Экспорт строки заголовка без заголовка в Excel
     *
           * @param title заголовок таблицы
           * Сбор данных набора данных @param
           * @param out выходной поток
           * @param версии 2003 или 2007, версия 2003 будет сгенерирована по умолчанию, если не передана
     * @return void
     * @author 
     * @date 2018-8-2
     */
    public void exportExcel(String title, Collection<T> dataset, OutputStream out, String version) {
        if (StringUtils.isEmpty(version) || EXCEL_FILE_2003.equals(version.trim())) {
            exportExcel2003(title, null, dataset, out, "yyyy-MM-dd hh:mm:ss");
        } else {
            exportExcel2007(title, null, dataset, out, "yyyy-MM-dd hh:mm:ss");
        }
    }

    /**
           * Описание функции Экспорт в Excel со строкой заголовка
     *
           * @param title заголовок таблицы
           * Коллекция заголовков заголовков @param
           * Сбор данных набора данных @param
           * @param out выходной поток
           * @param версии 2003 или 2007, версия 2003 будет сгенерирована по умолчанию, если не передана
     * @return void
     * @author 
     * @date 2018-8-2
     */
    public void exportExcel(String title, String[] headers, Collection<T> dataset, OutputStream out, String version) {
        if (StringUtils.isBlank(version) || EXCEL_FILE_2003.equals(version.trim())) {
            exportExcel2003(title, headers, dataset, out, "yyyy-MM-dd hh:mm:ss");
        } else {
            exportExcel2007(title, headers, dataset, out, "yyyy-MM-dd hh:mm:ss");
        }
    }

    /**
           * Описание функции
           * Общий метод экспорта в Excel, используйте механизм отражения для просмотра всех полей объекта и записи данных в файл Excel.
           * Эта версия генерирует файлы старше 2007 года (суффикс файла: xlsx)
     *
           * @param title название таблицы title
           * Коллекция заголовков таблицы заголовков @param
           * @param dataset Коллекция данных, которую необходимо отобразить, и объекты классов, соответствующие стилю JavaBean, должны быть помещены в эту коллекцию. Поддерживается этим методом
           * Типы данных атрибутов JavaBean включают основные типы данных и String, Date.
           * @param out Объект потока, связанный с устройством вывода, вы можете экспортировать документ EXCEL в локальный файл или в сеть.
           * @param pattern Если есть данные времени, установите формат вывода. Значение по умолчанию - «гггг-ММ-дд чч: мм: сс».
     * @return void
     * @author 
     * @date 2018-8-2
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    public void exportExcel2007(String title, String[] headers, Collection<T> dataset, OutputStream out, String pattern) {
        // Объявить книгу
        XSSFWorkbook workbook = new XSSFWorkbook();
        // Создаем таблицу
        XSSFSheet sheet = workbook.createSheet(title);
        // Устанавливаем ширину столбца таблицы по умолчанию на 20 байт
        sheet.setDefaultColumnWidth(20);
        // Создаем стиль
        XSSFCellStyle style = workbook.createCellStyle();

        // Устанавливаем эти стили (заголовок)
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setFillForegroundColor(new XSSFColor(Color.GRAY));
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setAlignment(HorizontalAlignment.CENTER);
        // Создаем шрифт
        XSSFFont font = workbook.createFont();
        font.setBold(true);
        font.setFontName("Сонг Ти");
        font.setColor(new XSSFColor(Color.BLACK));
        font.setFontHeightInPoints((short) 11);
        // Применяем шрифт к текущему стилю
        style.setFont(font);

        // Создание и установка другого стиля (содержимого)
        XSSFCellStyle style2 = workbook.createCellStyle();
        style2.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style2.setFillForegroundColor(new XSSFColor(Color.WHITE));
        style2.setBorderBottom(BorderStyle.THIN);
        style2.setBorderLeft(BorderStyle.THIN);
        style2.setBorderRight(BorderStyle.THIN);
        style2.setBorderTop(BorderStyle.THIN);
        style2.setAlignment(HorizontalAlignment.CENTER);
        style2.setVerticalAlignment(VerticalAlignment.CENTER);
        // Создаем другой шрифт
        XSSFFont font2 = workbook.createFont();
        font2.setBold(false);
        font2.setFontName("Сонг Ти");
        font2.setColor(new XSSFColor(Color.BLACK));
        font2.setFontHeightInPoints((short) 11);
        // Применяем шрифт к текущему стилю
        style2.setFont(font2);

        // Создание строки заголовка таблицы
        XSSFRow row = sheet.createRow(0);
        XSSFCell cellHeader;
        for (int i = 0; i < headers.length; i++) {
            cellHeader = row.createCell(i);
            cellHeader.setCellStyle(style);
            cellHeader.setCellValue(new XSSFRichTextString(headers[i]));
        }

        // Обходим данные коллекции, генерируем строки данных
        Iterator<T> it = dataset.iterator();
        int index = 0;
        T t;
        Field[] fields;
        Field field;
        XSSFRichTextString richString;
        Pattern p = Pattern.compile("^//d+(//.//d+)?$");
        Matcher matcher;
        String fieldName;
        String getMethodName;
        XSSFCell cell;
        Class tCls;
        Method getMethod;
        Object value;
        String textValue;
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        while (it.hasNext()) {
            index++;
            row = sheet.createRow(index);
            t = (T) it.next();
            // Используя отражение, в соответствии с порядком свойств JavaBean, динамически вызываем метод getXxx () для получения значения свойства
            // Если в классе сущности есть serialVersionUID, объявите serialVersionUID после всех атрибутов, иначе первый столбец будет пустым
            fields = t.getClass().getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                field = fields[i];
                fieldName = field.getName();
                if ("serialVersionUID".equals(fieldName)) {
                    continue;
                }
                cell = row.createCell(i);
                cell.setCellStyle(style2);
                getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                try {
                    tCls = t.getClass();
                    getMethod = tCls.getMethod(getMethodName, new Class[]{});
                    value = getMethod.invoke(t, new Object[]{});
                    // Выполняем принудительное преобразование типа после определения типа значения
                    textValue = null;
                    if (value instanceof Integer) {
                        cell.setCellValue((Integer) value);
                    } else if (value instanceof Float) {
                        textValue = String.valueOf((Float) value);
                        cell.setCellValue(textValue);
                    } else if (value instanceof Double) {
                        textValue = String.valueOf((Double) value);
                        cell.setCellValue(textValue);
                    } else if (value instanceof Long) {
                        cell.setCellValue((Long) value);
                    }
                    if (value instanceof Boolean) {
                        textValue = "Да";
                        if (!(Boolean) value) {
                            textValue = "нет";
                        }
                    } else if (value instanceof Date) {
                        textValue = sdf.format((Date) value);
                    } else {
                        // Другие типы данных обрабатываются просто как строки
                        if (value != null) {
                            textValue = value.toString();
                        }
                    }
                    if (textValue != null) {
                        matcher = p.matcher(textValue);
                        if (matcher.matches()) {
                            // Числа обрабатываются как двойные
                            cell.setCellValue(Double.parseDouble(textValue));
                        } else {
                            richString = new XSSFRichTextString(textValue);
                            cell.setCellValue(richString);
                        }
                    }
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (SecurityException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } finally {
                    // Очистить ресурсы
                }
            }
        }
        try {
            workbook.write(out);
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
           * Описание функции Универсальный метод экспорта в Excel, использующий механизм отражения для просмотра всех полей объекта и записи данных в файл Excel <br>
           * Этот метод создает версию Excel 2003 г., суффикс имени файла: xls
     *
           * @param title название таблицы title
           * Коллекция заголовков таблицы заголовков @param
           * @param dataset Коллекция данных, которая должна быть отображена, и объекты классов, соответствующих стилю JavaBean, должны быть помещены в коллекцию. Поддерживается этим методом
           * Типы данных атрибутов JavaBean включают основные типы данных и String, Date
           * @param out Объект потока, связанный с устройством вывода, которое может экспортировать документ EXCEL в локальный файл или в сеть.
           * @param pattern Если есть данные времени, установите формат вывода. Значение по умолчанию - «гггг-ММ-дд чч: мм: сс».
     * @return void
     * @author 
     * @date 2018-8-2
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    public void exportExcel2003(String title, String[] headers, Collection<T> dataset, OutputStream out, String pattern) {
        // Объявить книгу
        HSSFWorkbook workbook = new HSSFWorkbook();
        // Создаем таблицу
        HSSFSheet sheet = workbook.createSheet(title);
        // Устанавливаем ширину столбца таблицы по умолчанию равной 15 байтам
        sheet.setDefaultColumnWidth(20);
        // Создаем стиль
        HSSFCellStyle style = workbook.createCellStyle();
        // устанавливаем эти стили
        style.setFillForegroundColor(HSSFColor.HSSFColorPredefined.GREY_50_PERCENT.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setAlignment(HorizontalAlignment.CENTER);
        // Создаем шрифт
        HSSFFont font = workbook.createFont();
        font.setBold(true);
        font.setFontName("Сонг Ти");
        font.setColor(HSSFColor.HSSFColorPredefined.WHITE.getIndex());
        font.setFontHeightInPoints((short) 11);
        // Применяем шрифт к текущему стилю
        style.setFont(font);
        // Создание и установка другого стиля
        HSSFCellStyle style2 = workbook.createCellStyle();
        style2.setFillForegroundColor(HSSFColor.HSSFColorPredefined.WHITE.getIndex());
        style2.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style2.setBorderBottom(BorderStyle.THIN);
        style2.setBorderLeft(BorderStyle.THIN);
        style2.setBorderRight(BorderStyle.THIN);
        style2.setBorderTop(BorderStyle.THIN);
        style2.setAlignment(HorizontalAlignment.CENTER);
        style2.setVerticalAlignment(VerticalAlignment.CENTER);
        // Создаем другой шрифт
        HSSFFont font2 = workbook.createFont();
        font2.setBold(false);
        // Применяем шрифт к текущему стилю
        style2.setFont(font2);

        // Создание строки заголовка таблицы
        HSSFRow row = sheet.createRow(0);
        HSSFCell cellHeader;
        for (int i = 0; i < headers.length; i++) {
            cellHeader = row.createCell(i);
            cellHeader.setCellStyle(style);
            cellHeader.setCellValue(new HSSFRichTextString(headers[i]));
        }

        // Обходим данные коллекции, генерируем строки данных
        Iterator<T> it = dataset.iterator();
        int index = 0;
        T t;
        Field[] fields;
        Field field;
        HSSFRichTextString richString;
        Pattern p = Pattern.compile("^//d+(//.//d+)?$");
        Matcher matcher;
        String fieldName;
        String getMethodName;
        HSSFCell cell;
        Class tCls;
        Method getMethod;
        Object value;
        String textValue;
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        while (it.hasNext()) {
            index++;
            row = sheet.createRow(index);
            t = (T) it.next();
            // Используя отражение, в соответствии с порядком свойств JavaBean, динамически вызываем метод getXxx () для получения значения свойства
            // Если в классе сущности есть serialVersionUID, объявите serialVersionUID после всех атрибутов, иначе первый столбец будет пустым
            fields = t.getClass().getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                field = fields[i];
                fieldName = field.getName();
                if ("serialVersionUID".equals(fieldName)) {
                    continue;
                }
                cell = row.createCell(i);
                cell.setCellStyle(style2);
                getMethodName = "get" + fieldName.substring(0, 1).toUpperCase()
                        + fieldName.substring(1);
                try {
                    tCls = t.getClass();
                    getMethod = tCls.getMethod(getMethodName, new Class[]{});
                    value = getMethod.invoke(t, new Object[]{});
                    // После определения типа значения выполняем принудительное преобразование типа
                    textValue = null;
                    if (value instanceof Integer) {
                        cell.setCellValue((Integer) value);
                    } else if (value instanceof Float) {
                        textValue = String.valueOf((Float) value);
                        cell.setCellValue(textValue);
                    } else if (value instanceof Double) {
                        textValue = String.valueOf((Double) value);
                        cell.setCellValue(textValue);
                    } else if (value instanceof Long) {
                        cell.setCellValue((Long) value);
                    }
                    if (value instanceof Boolean) {
                        textValue = "Да";
                        if (!(Boolean) value) {
                            textValue = "нет";
                        }
                    } else if (value instanceof Date) {
                        textValue = sdf.format((Date) value);
                    } else {
                        // Другие типы данных обрабатываются просто как строки
                        if (value != null) {
                            textValue = value.toString();
                        }
                    }
                    if (textValue != null) {
                        matcher = p.matcher(textValue);
                        if (matcher.matches()) {
                            // Числа обрабатываются как двойные
                            cell.setCellValue(Double.parseDouble(textValue));
                        } else {
                            richString = new HSSFRichTextString(textValue);
                            cell.setCellValue(richString);
                        }
                    }
                } catch (SecurityException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } finally {
                    // Очистить ресурсы
                }
            }
        }
        try {
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
           * Экспорт в Excel
     *
           * @param заголовки данных заголовков
           * @param valueList тело данных
           * @param fileName Имя файла Excel
           * @param sheetName имя первой страницы листа
     * @param response
     */
    public void listToExcel(String[] titles, List<List<Object>> valueList, String fileName, String sheetName, HttpServletResponse response) {
        try {
            response.setContentType("application/x-download");
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.addHeader("Content-Disposition", "attachement;filename=" + fileName);
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFCellStyle cellStyle = workbook.createCellStyle();
            HSSFDataFormat format = workbook.createDataFormat();
            HSSFSheet sheet = workbook.createSheet();
            if (sheetName != null && sheetName.trim().length() >0 ) {
                workbook.setSheetName(0, sheetName);
            }
            HSSFRow row = sheet.createRow(0);
            HSSFCell cell;
            Set<String> set = new HashSet<>();
            // Строим заголовок
            for (int i = 0; i < titles.length; i++) {
                String title = titles[i];
//                cell = row.createCell[i];
                cell = row.createCell(i);
                cell.setCellType(CellType.STRING);
                cell.setCellValue(title);
            }
            // Строим таблицу
            for (int j = 0; j < valueList.size(); j++) {
                List<Object> values = valueList.get(j);
                row = sheet.createRow(j + 1);
                for (int m = 0; m < values.size(); m++) {
                    cell = row.createCell(m);
                    cell.setCellType(CellType.STRING);
                    if (values.get(m) != null) {
                        cell.setCellValue(values.get(m).toString());
                    } else {
                        cell.setCellValue("");
                    }
                }
            }
            OutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
           * Получить значение ячейки Excel
     *
     * @param cell
     * @return
     */
    public String getCellValue(Cell cell) {
        String value = "";
        if (cell != null) {
            switch (cell.getCellTypeEnum()) {
                case NUMERIC:  // цифровой
                    value = cell.getNumericCellValue() + "";
                    if (HSSFDateUtil.isCellDateFormatted(cell)) {
                        Date date = cell.getDateCellValue();
                        if (date != null) {
                            value = new SimpleDateFormat("yyyy-MM-dd").format(date);// Форматирование даты
                        } else {
                            value = "";
                        }
                    } else {
                        // При парсинге ячейки числовой тип по умолчанию двойной, но желаемый целочисленный тип нужно отформатировать, что очень важно
                        value = new DecimalFormat("0").format(cell.getNumericCellValue());
                    }
                    break;
                case STRING://Строка
                    value = cell.getStringCellValue();
                    break;
                case BOOLEAN://логический тип
                    value = cell.getBooleanCellValue() + "";
                    break;
                case BLANK://Нулевое значение
                    value = "";
                    break;
                case ERROR://Тип ошибки
                    value = "недопустимый символ";
                    break;
                default:
                    value = «Неизвестный тип»;
            }
        }
        return value.trim();
    }


}

import java.io.File;

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

import org.apache.poi.xssf.usermodel.XSSFRow;

import org.apache.poi.xssf.usermodel.XSSFSheet;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;

import java.util.Map;

import java.util.Set;

import java.util.TreeMap;

public class WriteDataToExcel {

    public static void main(String[] args) throws Exception

    {

        XSSFWorkbook workbook = new XSSFWorkbook();

        XSSFSheet spreadsheet

            = workbook.createSheet(" Student Data ");

        XSSFRow row;

        Map<String, Object[]> studentData

            = new TreeMap<String, Object[]>();

        studentData.put(

            "1",

            new Object[] { "Roll No", "NAME", "Year" });

        studentData.put("2", new Object[] { "128", "Aditya",

                                            "2nd year" });

        studentData.put(

            "3",

            new Object[] { "129", "Narayana", "2nd year" });

        studentData.put("4", new Object[] { "130", "Mohan",

                                            "2nd year" });

        studentData.put("5", new Object[] { "131", "Radha",

                                            "2nd year" });

        studentData.put("6", new Object[] { "132", "Gopal",

                                            "2nd year" });

        Set<String> keyid = studentData.keySet();

        int rowid = 0;

        for (String key : keyid) {

            row = spreadsheet.createRow(rowid++);

            Object[] objectArr = studentData.get(key);

            int cellid = 0;

            for (Object obj : objectArr) {

                Cell cell = row.createCell(cellid++);

                cell.setCellValue((String)obj);

            }

        }

        FileOutputStream out = new FileOutputStream(

            new File("C:/savedexcel/GFGsheet.xlsx"));

        workbook.write(out);

        out.close();

    }

}

I was searching the internet for an answer to exporting data from my Java desktop app to Excel and I came across the Apache POI API. Then I found out that the JDBC would work, and then I stumbled on JExcel. Are they all equally good, or should I focus on the best among them, and which is it?

Cheers.

wassimans's user avatar

wassimans

8,33210 gold badges48 silver badges58 bronze badges

asked Apr 17, 2012 at 7:49

Akinwale Agbaje's user avatar

Akinwale AgbajeAkinwale Agbaje

3153 gold badges6 silver badges17 bronze badges

6

Why so complicated?

Just TAB separate your columns and write the output to plain text file with an «.xls» extension?

That way, all you need to do is open the generated «.xls» file. Even though it’s actually just a TAB-separated text file, Excel will open it and automatically treat each tab as a new column.

No idea why people still use csv files, frankly.

answered Jan 9, 2013 at 11:16

zeb's user avatar

5

I might be late to answer this, but I guess your correct choice would be Jxls. I faced a similar scenario in my module where I had to retain a certain template like logo,color,col-span,fixed column… So that’s very hectic to write a separate java code and design it.

Jxls core is poi and syntactically similar to jstl, all you need is to map a array-list of bean with desired column in excel

Tadija Malić's user avatar

answered Jul 20, 2012 at 4:40

sayannayas's user avatar

sayannayassayannayas

7649 silver badges15 bronze badges

If the exported excel file is large, maybe there will be outofmemory exception. (It is the problem I met before, I don’t know whether it is improved now.)

The most easiest way is to export as CSV file.

answered Apr 17, 2012 at 9:17

Mavlarn's user avatar

MavlarnMavlarn

3,7572 gold badges36 silver badges57 bronze badges

The best way is to do Tab separation for column and n for row. Save as .xls.

Perfect solution :) ty Zeb

answered Jun 16, 2015 at 22:22

Ashish Yeole's user avatar

2

In the engineering world, we often gather lots of data that we need to store and display in a spreadsheet format. Microsoft’s Excel is probably the most popular spreadsheet format there are out there. In order to read and write to an excel file from Java, we need the Apache POI library. The POI library actually handle all kinds of Microsoft document format, however, we will only deal with Excel files today.

Apache POI Library Homepage
http://poi.apache.org/

Apache POI’s Detailed Programming Guide
http://poi.apache.org/spreadsheet/quick-guide.html

So here’s a simple application that I wrote to demonstrate how to export data to an excel file and read back into the program from it.

Basic POI Library Workflow
Open New Workbook => Create New Sheets => Create New Rows => Create New Cells

*Make sure to add both the poi and the poi-ooxml jar file to the libraries folder in Netbeans. The Class WorkbookFactory used to import the data is located in poi-ooxml.

//Yu Hin Hau
//Importing and Exporting to Excel
//June 14, 2012

import java.io.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
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.ss.usermodel.WorkbookFactory;

public class Main {

    public static void main(String[] args) throws FileNotFoundException, IOException, InvalidFormatException
    {
        //Create 2D Array of Data
        double[][] value = new double[5][5];

        for(int i = 0; i < value.length; i++)
            for(int j = 0; j < value[i].length; j++)
                value[i][j] = i+j;

        //Export Data to Excel File
        exportData("data.xls","i+j",value);

        //Import Data from Excel File
        double[][] data = importData("data.xls", 0);

        //Display Data from File
        for(int i = 0; i < data.length; i++)
        {
            for(int j = 0; j < data[i].length; j++)
                System.out.print(data[i][j]+"t");

            System.out.println();
        }

    }

    public static void exportData(String fileName, String tabName, double[][] data) throws FileNotFoundException, IOException
    {
        //Create new workbook and tab
        Workbook wb = new HSSFWorkbook();
        FileOutputStream fileOut = new FileOutputStream(fileName);
        Sheet sheet = wb.createSheet(tabName);

        //Create 2D Cell Array
        Row[] row = new Row[data.length];
        Cell[][] cell = new Cell[row.length][];

        //Define and Assign Cell Data from Given
        for(int i = 0; i < row.length; i ++)
        {
            row[i] = sheet.createRow(i);
            cell[i] = new Cell[data[i].length];

            for(int j = 0; j < cell[i].length; j ++)
            {
                cell[i][j] = row[i].createCell(j);
                cell[i][j].setCellValue(data[i][j]);
            }

        }

        //Export Data
        wb.write(fileOut);
        fileOut.close();

    }

    public static double[][] importData(String fileName, int tabNumber) throws FileNotFoundException, IOException, InvalidFormatException
    {

        double[][] data;

        //Create Workbook from Existing File
        InputStream fileIn = new FileInputStream(fileName);
        Workbook wb = WorkbookFactory.create(fileIn);
        Sheet sheet = wb.getSheetAt(tabNumber);

        //Define Data & Row Array and adjust from Zero Base Numer
        data = new double[sheet.getLastRowNum()+1][];
        Row[] row = new Row[sheet.getLastRowNum()+1];
        Cell[][] cell = new Cell[row.length][];

        //Transfer Cell Data to Local Variable
        for(int i = 0; i < row.length; i++)
        {
            row[i] = sheet.getRow(i);

            //Note that cell number is not Zero Based
            cell[i] = new Cell[row[i].getLastCellNum()];
            data[i] = new double[row[i].getLastCellNum()];

            for(int j = 0; j < cell[i].length; j++)
            {
                cell[i][j] = row[i].getCell(j);
                data[i][j] = cell[i][j].getNumericCellValue();
            }

        }

        fileIn.close();
        return data;
    }

}

Details
Written by  
Last Updated on 22 October 2019   |   Print  Email

This tutorial helps you write Java code to export data from a table in database to an Excel file – a very common task of a software program. To read data from database, we use JDBC with appropriate JDBC driver (MySQL is used in this tutorial). And to generate Excel file, we use Apache POI library.

Suppose that we have a table with the following structure:

table review structure

This table contains some data like this:

data-in-table

I will guide you how to code simple program that exports data from this table to Excel 2007+ format (XSLX), and an advanced program that can export data from any table.

First, make sure that you specify the dependencies for MySQL JDBC driver and Apache POI API for Excel in Maven’s pom.xml file:

<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<version>5.1.46</version>
	<scope>runtime</scope>
</dependency>
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi-ooxml</artifactId>
	<version>4.1.0</version>
</dependency>

Next, let’s see the code examples.

 

The following code is for a simple Java program that connects to a MySQL database, reads all rows from the Review table and writes the data to an Excel file:

package net.codejava;

import java.io.*;
import java.sql.*;

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

/**
 * A simple Java program that exports data from database to Excel file.
 * @author Nam Ha Minh
 * (C) Copyright codejava.net
 */
public class SimpleDb2ExcelExporter {

	public static void main(String[] args) {
		new SimpleDb2ExcelExporter().export();
	}
	
	public void export() {
		String jdbcURL = "jdbc:mysql://localhost:3306/sales";
		String username = "root";
		String password = "password";

		String excelFilePath = "Reviews-export.xlsx";

		try (Connection connection = DriverManager.getConnection(jdbcURL, username, password)) {
			String sql = "SELECT * FROM review";

			Statement statement = connection.createStatement();

			ResultSet result = statement.executeQuery(sql);

			XSSFWorkbook workbook = new XSSFWorkbook();
			XSSFSheet sheet = workbook.createSheet("Reviews");

			writeHeaderLine(sheet);

			writeDataLines(result, workbook, sheet);

			FileOutputStream outputStream = new FileOutputStream(excelFilePath);
			workbook.write(outputStream);
			workbook.close();

			statement.close();

		} catch (SQLException e) {
			System.out.println("Datababse error:");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("File IO error:");
			e.printStackTrace();
		}
	}

	private void writeHeaderLine(XSSFSheet sheet) {

		Row headerRow = sheet.createRow(0);

		Cell headerCell = headerRow.createCell(0);
		headerCell.setCellValue("Course Name");

		headerCell = headerRow.createCell(1);
		headerCell.setCellValue("Student Name");

		headerCell = headerRow.createCell(2);
		headerCell.setCellValue("Timestamp");

		headerCell = headerRow.createCell(3);
		headerCell.setCellValue("Rating");

		headerCell = headerRow.createCell(4);
		headerCell.setCellValue("Comment");
	}

	private void writeDataLines(ResultSet result, XSSFWorkbook workbook, 
			XSSFSheet sheet) throws SQLException {
		int rowCount = 1;

		while (result.next()) {
			String courseName = result.getString("course_name");
			String studentName = result.getString("student_name");
			float rating = result.getFloat("rating");
			Timestamp timestamp = result.getTimestamp("timestamp");
			String comment = result.getString("comment");

			Row row = sheet.createRow(rowCount++);

			int columnCount = 0;
			Cell cell = row.createCell(columnCount++);
			cell.setCellValue(courseName);

			cell = row.createCell(columnCount++);
			cell.setCellValue(studentName);

			cell = row.createCell(columnCount++);

			CellStyle cellStyle = workbook.createCellStyle();
			CreationHelper creationHelper = workbook.getCreationHelper();
			cellStyle.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));
			cell.setCellStyle(cellStyle);

			cell.setCellValue(timestamp);

			cell = row.createCell(columnCount++);
			cell.setCellValue(rating);

			cell = row.createCell(columnCount);
			cell.setCellValue(comment);

		}
	}

}

Note that the writeHeaderLine() method writes the column names of the table to the first line in the Excel file. The column names are known beforehand and fixed. The first column (ID) is omitted.

The writeDataLines() method iterates over all rows in the result set returned from the database, and writes data to the Excel file. Note that there’s a datetime value so a cell style is created to format value as datetime.

Run this program, you will see the Reviews-export.xlsx file is generated in the same directory of the program. Open this file by Microsoft Excel application and you will see:

simple-excel-exported

 

2. Advanced Java code example to export data from database to Excel file

Let’s see the code of a more advanced program that can export data from any table in the database to Excel file. Following is the full code:

package net.codejava;

import java.io.*;
import java.sql.*;
import java.text.*;
import java.util.Date;

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

/**
 * An advanced Java program that exports data from any table to Excel file.
 * @author Nam Ha Minh
 * (C) Copyright codejava.net
 */
public class AdvancedDb2ExcelExporter {

	public static void main(String[] args) {
		AdvancedDb2ExcelExporter exporter = new AdvancedDb2ExcelExporter();
		exporter.export("Review");
		exporter.export("Product");
	}

	private String getFileName(String baseName) {
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
		String dateTimeInfo = dateFormat.format(new Date());
		return baseName.concat(String.format("_%s.xlsx", dateTimeInfo));
	}

	public void export(String table) {
		String jdbcURL = "jdbc:mysql://localhost:3306/sales";
		String username = "root";
		String password = "password";

		String excelFilePath = getFileName(table.concat("_Export"));

		try (Connection connection = DriverManager.getConnection(jdbcURL, username, password)) {
			String sql = "SELECT * FROM ".concat(table);

			Statement statement = connection.createStatement();

			ResultSet result = statement.executeQuery(sql);

			XSSFWorkbook workbook = new XSSFWorkbook();
			XSSFSheet sheet = workbook.createSheet(table);

			writeHeaderLine(result, sheet);

			writeDataLines(result, workbook, sheet);

			FileOutputStream outputStream = new FileOutputStream(excelFilePath);
			workbook.write(outputStream);
			workbook.close();

			statement.close();

		} catch (SQLException e) {
			System.out.println("Datababse error:");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("File IO error:");
			e.printStackTrace();
		}
	}

	private void writeHeaderLine(ResultSet result, XSSFSheet sheet) throws SQLException {
		// write header line containing column names
		ResultSetMetaData metaData = result.getMetaData();
		int numberOfColumns = metaData.getColumnCount();

		Row headerRow = sheet.createRow(0);

		// exclude the first column which is the ID field
		for (int i = 2; i <= numberOfColumns; i++) {
			String columnName = metaData.getColumnName(i);
			Cell headerCell = headerRow.createCell(i - 2);
			headerCell.setCellValue(columnName);
		}
	}

	private void writeDataLines(ResultSet result, XSSFWorkbook workbook, XSSFSheet sheet) 
			throws SQLException {
		ResultSetMetaData metaData = result.getMetaData();
		int numberOfColumns = metaData.getColumnCount();

		int rowCount = 1;

		while (result.next()) {
			Row row = sheet.createRow(rowCount++);

			for (int i = 2; i <= numberOfColumns; i++) {
				Object valueObject = result.getObject(i);

				Cell cell = row.createCell(i - 2);

				if (valueObject instanceof Boolean) 
					cell.setCellValue((Boolean) valueObject);
				else if (valueObject instanceof Double)
					cell.setCellValue((double) valueObject);
				else if (valueObject instanceof Float)
					cell.setCellValue((float) valueObject);
				else if (valueObject instanceof Date) {
					cell.setCellValue((Date) valueObject);
					formatDateCell(workbook, cell);
				} else cell.setCellValue((String) valueObject); 

			}

		}
	}

	private void formatDateCell(XSSFWorkbook workbook, Cell cell) {
		CellStyle cellStyle = workbook.createCellStyle();
		CreationHelper creationHelper = workbook.getCreationHelper();
		cellStyle.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));
		cell.setCellStyle(cellStyle);
	}
}

In this program, the name of the Excel file is generated based on table name followed by the current datetime – as you can see in the getFileName() method. The writeHeaderLine() and writeDataLines() methods use ResultSetMetaData to read column names so this program can work with any table.

Note that this program excludes the first column of the table, which is supposed to be the ID column.

And you can specify the table name when running this program, for example:

AdvancedDb2ExcelExporter exporter = new AdvancedDb2ExcelExporter();
exporter.export("Review");
exporter.export("Product");

That’s a couple of example programs that show you how to export data from database to Excel file. To learn more about writing Excel file, read this tutorial: How to Write Excel Files in Java using Apache POI

 

Other Java Coding Tutorials:

  • Java code example to import data from Excel to database
  • How to display images from database in JSP page with Java Servlet
  • How to implement remember password (remember me) for Java web application
  • How to code login and logout with Java Servlet, JSP and MySQL
  • How to Code Hit Counter for Java web application
  • 10 Common Mistakes Every Beginner Java Programmer Makes
  • 10 Java Core Best Practices Every Java Programmer Should Know
  • How to become a good programmer? 13 tasks you should practice now
  • How to calculate MD5 and SHA hash values in Java
  • Java File Encryption and Decryption Example

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Add comment

Понравилась статья? Поделить с друзьями:

А вот еще интересные статьи:

  • Как импортировать csv файл excel
  • Как именуются ячейки excel
  • Как именуются строки в программе ms excel
  • Как именуется документ в word
  • Как именовать ячейки в excel

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии