国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

java poi導(dǎo)入Excel、導(dǎo)出excel

這篇具有很好參考價值的文章主要介紹了java poi導(dǎo)入Excel、導(dǎo)出excel。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

java poi導(dǎo)入Excel、導(dǎo)出excel

導(dǎo)出meven架包

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.1</version>
        </dependency>

導(dǎo)入Excel


    public void uploadFile(HttpServletRequest request, HttpServletResponse response, @RequestParam(value="file",required = false) MultipartFile file) {
        return import(request, response, file);
    }

	public void import(HttpServletRequest request, HttpServletResponse response, MultipartFile file) {
        long startTime = System.currentTimeMillis();
        //解析Excel
        List<DTO> excelInfo = ReadPatientExcelUtil.getExcelInfo(file);
        if(excelInfo!=null && excelInfo.size()>0){
            for (int i = 0; i < excelInfo.size(); i++) {
                DTO dto = excelInfo.get(i);
            }
        }else{
            System.out.println("導(dǎo)入失敗,請注意參數(shù)格式!");
        }
        long endTime = System.currentTimeMillis();
        String time = String.valueOf((endTime - startTime) / 1000);
        log.info("導(dǎo)入數(shù)據(jù)用時:"+time+"秒");
        return ResponseMsg.success("導(dǎo)入成功!");
    }

	    

ReadPatientExcelUtil

import com.ly.directserver.dto.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.NumberToTextConverter;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/***
 * 解析導(dǎo)入Excel數(shù)據(jù)
 * @author manba
 */
@Slf4j
public class ReadPatientExcelUtil {

    //總行數(shù)
    private static int totalRows = 0;
    //總條數(shù)
    private static int totalCells = 0;
    //錯誤信息接收器
    private static String errorMsg;
    
    /***
     * 讀取Excel
     * @param mFile
     * @return
     */
    public static List<DTO> getExcelInfo(MultipartFile mFile) {
        String fileName = mFile.getOriginalFilename();//獲取文件名
        try {
            if (!validateExcel(fileName)) {// 驗證文件名是否合格
                return null;
            }
            boolean isExcel2003 = true;// 根據(jù)文件名判斷文件是2003版本還是2007版本
            if (isExcel2007(fileName)) {
                isExcel2003 = false;
            }
            List<DTO> agentList = getExcel(mFile.getInputStream(), isExcel2003);
            return agentList;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

	    public static List<DTO> getAgentExcel(InputStream is, boolean isExcel2003) {
        try {
            Workbook wb = null;
            if (isExcel2003) {// 當(dāng)excel是2003時,創(chuàng)建excel2003
                wb = new HSSFWorkbook(is);
            } else {// 當(dāng)excel是2007時,創(chuàng)建excel2007
                wb = new XSSFWorkbook(is);
            }
            List<DTO> DTOS = readExcelValue(wb);// 讀取Excel里面客戶的信息
            return DTOS;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

	private static List<DTO> readExcelValue(Workbook wb) {
        //默認會跳過第一行標(biāo)題
        // 得到第一個shell
        Sheet sheet = wb.getSheetAt(0);
        // 得到Excel的行數(shù)
        totalRows = sheet.getPhysicalNumberOfRows();
        // 得到Excel的列數(shù)(前提是有行數(shù))
        if (totalRows > 1 && sheet.getRow(0) != null) {
            totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
        }
        List<DTO> DTOS = new ArrayList<>();
        // 循環(huán)Excel行數(shù)
        for (int r = 1; r < totalRows; r++) {
            Row row = sheet.getRow(r);
            if (row == null) {
                continue;
            }
            DTO DTO = new DTO();
            // 循環(huán)Excel的列
            for (int c = 0; c < totalCells ; c++) {
                Cell cell = row.getCell(c);
                if (null != cell) {
                    if (c == 0) {           //第一列
                        //如果是純數(shù)字
                        if (cell.getCellTypeEnum() == CellType.NUMERIC) {
                            cell.setCellType(CellType.NUMERIC);
                            int a =(int) cell.getNumericCellValue();
                        }
                    }  else if (c == 1) {
                    //如果是double
                        if (cell.getCellTypeEnum() == CellType.NUMERIC) {
                            cell.setCellType(CellType.NUMERIC);
                        }
                        double stringCellValue = cell.getNumericCellValue();
                    } else if (c == 2) {
                        if (cell.getCellTypeEnum() == CellType.STRING) {
                            cell.setCellType(CellType.STRING);
                            //如果是字符串
                            String str = cell.getStringCellValue();
                        }else if (cell.getCellTypeEnum() == CellType.NUMERIC) {
                            cell.setCellType(CellType.NUMERIC);
                            //如果是數(shù)字,需要轉(zhuǎn)換為字符串
                            String desc = NumberToTextConverter.toText(cell.getNumericCellValue());
                        }
                    }
                }
            }
            //將excel解析出來的數(shù)據(jù)賦值給對象添加到list中
            // 添加到list
            DTOS.add(DTO);
        }
        return DTOS;
    }
    }

導(dǎo)出Excel

	    public void exportCollectRecord(HttpServletResponse res){
        File file = createExcelFile();
        FileUtils.downloadFile(res, file, file.getName());
    }

	public static File createExcelFile(List<DTO> list) {
        Workbook workbook = new XSSFWorkbook();
        //創(chuàng)建一個sheet,括號里可以輸入sheet名稱,默認為sheet0
        Sheet sheet = workbook.createSheet();
        Row row0 = sheet.createRow(0);
        int columnIndex = 0;
        row0.createCell(columnIndex).setCellValue("xxx");
        row0.createCell(++columnIndex).setCellValue("xxx");
        row0.createCell(++columnIndex).setCellValue("xxx");

        for (int i = 0; i < list.size(); i++) {
            DTO dto = list.get(i);

            Row row = sheet.createRow(i + 1);
            for (int j = 0; j < columnIndex + 2; j++) {
                row.createCell(j);
            }
            columnIndex = 0;
            row.getCell(columnIndex).setCellValue("xxx");
            row.getCell(++columnIndex).setCellValue("xxx");
            row.getCell(++columnIndex).setCellValue("xxx");
           
            
        }
        //調(diào)用PoiUtils工具包
        return PoiUtils.createExcelFile(workbook, DateUtils.fmtDateToStr(new Date(), "yyyy-MM-dd HH_mm_ss") );
    }

	
	

PoiUtils

import org.apache.poi.ss.usermodel.Workbook;
import java.io.*;

public class PoiUtils {

    /**
     * 生成Excel文件
     * @param workbook
     * @param fileName
     * @return
     */
    public static File createExcelFile(Workbook workbook, String fileName) {
        OutputStream stream = null;
        File file = null;
        try {
            //用了createTempFile,這是創(chuàng)建臨時文件,系統(tǒng)會自動給你的臨時文件編號,所以后面有號碼,你用createNewFile的話就完全按照你指定的名稱來了
            file = File.createTempFile(fileName, ".xlsx");
            stream = new FileOutputStream(file.getAbsoluteFile());
            workbook.write(stream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //這里調(diào)用了IO工具包控制開關(guān)
            IOUtils.closeQuietly(workbook);
            IOUtils.closeQuietly(stream);
        }
        return file;
    }

}

FileUtils文章來源地址http://www.zghlxwxcb.cn/news/detail-610281.html

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.lang.reflect.Method;
import java.security.MessageDigest;

public class FileUtils {

    /**
     * 下載文件
     * @param response
     * @param file
     * @param newFileName
     */
    public static void downloadFile(HttpServletResponse response, File file, String newFileName) {
        try {
            response.setHeader("Content-Disposition", "attachment; filename=" + new String(newFileName.getBytes("ISO-8859-1"), "UTF-8"));
            BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
            InputStream is = new FileInputStream(file.getAbsolutePath());
            BufferedInputStream bis = new BufferedInputStream(is);
            int length = 0;
            byte[] temp = new byte[1 * 1024 * 10];
            while ((length = bis.read(temp)) != -1) {
                bos.write(temp, 0, length);
            }
            bos.flush();
            bis.close();
            bos.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 將輸入流使用指定編碼轉(zhuǎn)化為字符串
    public static String inputStream2String(InputStream inputStream, String charset) throws Exception {
        // 建立輸入流讀取類
        InputStreamReader reader = new InputStreamReader(inputStream, charset);
        // 設(shè)定每次讀取字符個數(shù)
        char[] data = new char[512];
        int dataSize = 0;
        // 循環(huán)讀取
        StringBuilder stringBuilder = new StringBuilder();
        while ((dataSize = reader.read(data)) != -1) {
            stringBuilder.append(data, 0, dataSize);
        }
        return stringBuilder.toString();
    }

    private static DocumentBuilderFactory documentBuilderFactory = null;

    public static <T> T parseXml2Obj(String xml, Class<T> tclass) throws Exception {
        if (isEmpty(xml)) throw new NullPointerException("要解析的xml字符串不能為空。");
        if (documentBuilderFactory == null) { // 文檔解析器工廠初始
            documentBuilderFactory = DocumentBuilderFactory.newInstance();
        }
        // 拿到一個文檔解析器。
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        // 準(zhǔn)備數(shù)據(jù)并解析。
        byte[] bytes = xml.getBytes("UTF-8");
        Document parsed = documentBuilder.parse(new ByteArrayInputStream(bytes));
        // 獲取數(shù)據(jù)
        T obj = tclass.newInstance();
        Element documentElement = parsed.getDocumentElement();
        NodeList childNodes = documentElement.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            Node item = childNodes.item(i);
            // 節(jié)點類型是 ELEMENT 才讀取值
            // 進行此判斷是因為如果xml不是一行,而是多行且有很好的格式的,就會產(chǎn)生一些文本的node,這些node內(nèi)容只有換行符或空格
            // 所以排除這些換行符和空格。
            if (item.getNodeType() == Node.ELEMENT_NODE) {
                String key = item.getNodeName();
                String value = item.getTextContent();
                // 拿到設(shè)置值的set方法。
                Method declaredMethod = tclass.getDeclaredMethod("set" + key, String.class);
                if (declaredMethod != null) {
                    declaredMethod.setAccessible(true);
                    declaredMethod.invoke(obj, value); // 設(shè)置值
                }
            }
        }
        return obj;
    }


    // 將二進制數(shù)據(jù)轉(zhuǎn)換為16進制字符串。
    public static String byte2HexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        for (byte b : src) {
            String hv = Integer.toHexString(b & 0xFF);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }
    // 對字符串進行sha1加簽
    public static String sha1(String context) throws Exception {
        // 獲取sha1算法封裝類
        MessageDigest sha1Digest = MessageDigest.getInstance("SHA-1");
        // 進行加密
        byte[] digestResult = sha1Digest.digest(context.getBytes("UTF-8"));
        // 轉(zhuǎn)換為16進制字符串
        return byte2HexString(digestResult);
    }
    public static boolean isEmpty(String value) {
        return value == null || value.length() == 0;
    }

}

到了這里,關(guān)于java poi導(dǎo)入Excel、導(dǎo)出excel的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • hutool poi、apache poi實現(xiàn)導(dǎo)入導(dǎo)出以及解析excel

    hutool poi、apache poi實現(xiàn)導(dǎo)入導(dǎo)出以及解析excel

    一、前言 看了例子之后后續(xù)需要更加深入學(xué)習(xí)或者更多理解其他API的話,建議看官方文檔。hutool項目是中國人維護的,有中文文檔,閱讀起來很方便。apache poi比較底層一點,可以更加自由去二次開發(fā)自己所需的功能。 hutool官方文檔 hutool官方gitee apache poi官方文檔 二、基于

    2024年02月09日
    瀏覽(24)
  • Excel 導(dǎo)入導(dǎo)出(前端處理:xslx)(后端處理:hutool+poi || Easy Excel )

    Excel 導(dǎo)入導(dǎo)出(前端處理:xslx)(后端處理:hutool+poi || Easy Excel )

    ? 目錄 Excel 導(dǎo)入導(dǎo)出(前端處理:xslx) 代碼示例 導(dǎo)入Excel數(shù)據(jù) 將數(shù)據(jù)封裝好后傳給后端? 導(dǎo)出數(shù)據(jù) 預(yù)覽(vue-office/excel\\\"……;docx-preview) Excel 導(dǎo)入導(dǎo)出(后端處理:hutool+poi || Easy Excel ) 前端 后端使用Hutool處理Excel 文件 Hutool-poi是針對Apache POI的封裝,因此需要用戶自行引入

    2024年01月24日
    瀏覽(38)
  • 使用POI和EasyExcel來實現(xiàn)excel文件的導(dǎo)入導(dǎo)出

    使用POI和EasyExcel來實現(xiàn)excel文件的導(dǎo)入導(dǎo)出

    廢話不多說咱們直接上干貨?。。?! 一.讀取Excel表格 【1】使用POI讀取excel表格中的數(shù)據(jù) POI還可以操作我們這個word文檔等等,他不僅僅只能弄Excel,而JXI只能操作excel 1.POI的結(jié)構(gòu),我們可以更具文件的類去選擇 相關(guān)的對象我當(dāng)前是使用的XLSX來操作的 HSSF - 提供讀寫Microsoft

    2024年02月05日
    瀏覽(26)
  • Apache POI實現(xiàn)Excel導(dǎo)入讀取數(shù)據(jù)和寫入數(shù)據(jù)并導(dǎo)出

    Apache POI POI介紹 Apache POI是用Java編寫的免費開源的跨平臺的Java API,Apache POI提供API給Java程序?qū)icrosoft Office格式檔案讀和寫的功能,其中使用最多的就是使用POI操作Excel文件。 maven坐標(biāo): POI結(jié)構(gòu): 入門案例 ExcelTest .java文件 從Excel文件讀取數(shù)據(jù)

    2024年02月12日
    瀏覽(32)
  • poi實現(xiàn)excel文件導(dǎo)入導(dǎo)出(基本數(shù)據(jù)導(dǎo)出、含格式導(dǎo)出、含批注導(dǎo)出、含圖片圖表導(dǎo)出)——springboot

    poi實現(xiàn)excel文件導(dǎo)入導(dǎo)出(基本數(shù)據(jù)導(dǎo)出、含格式導(dǎo)出、含批注導(dǎo)出、含圖片圖表導(dǎo)出)——springboot

    本文主要是介紹springboot + poi實現(xiàn)基本的excel文件導(dǎo)入導(dǎo)出,包含數(shù)據(jù)導(dǎo)出導(dǎo)入時數(shù)據(jù)的其他需求校驗,導(dǎo)出含有批注信息、導(dǎo)出含有圖片信息、導(dǎo)出含有圖表信息等的介紹等等,主要是一個demo盡可能簡單明了的來介紹相關(guān)功能即可。有什么問題可以在留言哦!并在文章末尾附

    2024年02月08日
    瀏覽(28)
  • Java使用POI導(dǎo)出Excel

    Java使用POI導(dǎo)出Excel

    在項目開發(fā)中往往需要使用到Excel的導(dǎo)入和導(dǎo)出,導(dǎo)入就是從Excel中導(dǎo)入到DB中,而導(dǎo)出就是從DB中查詢數(shù)據(jù)然后使用POI寫到Excel上。 操作Excel目前比較流行的就是 Apache POI 和阿里巴巴的 easyExcel ! 廢話不多說,開始擼起來!??! POI官網(wǎng);https://poi.apache.org/ POI官網(wǎng)API:https://poi.

    2024年02月04日
    瀏覽(36)
  • Java Poi導(dǎo)出Excel表格詳解

    Java Poi導(dǎo)出Excel表格詳解

    一、導(dǎo)出下面的表格 二、流程詳解 ??????? 1、導(dǎo)出excel需要先將數(shù)據(jù)準(zhǔn)備好 ??????? 2、創(chuàng)建工作傅對象SXSSFWorkbook ??????? 3、使用工作傅對象創(chuàng)建sheet對象(工作頁) ??????? 4、使用sheet對象創(chuàng)建行對象row(行對象) ??????? 5、使用row對象創(chuàng)建cell對象(單元格

    2024年02月10日
    瀏覽(28)
  • java poi實現(xiàn)Excel多級表頭導(dǎo)出

    java poi實現(xiàn)Excel多級表頭導(dǎo)出

    最近碰到一個導(dǎo)出,比較繁瑣,也查詢了許多博客,在其中一篇博客的基礎(chǔ)上修改,實現(xiàn)了最終想要的效果。話不多說,直接上效果圖 1.主代碼: 2.合并單元格 3.設(shè)置表頭單元格的寬度 4.填充數(shù)據(jù)(注:我這里的數(shù)據(jù)格式是ListMapString, Object類型,可以根據(jù)自己的實際情況來封

    2024年02月03日
    瀏覽(47)
  • java中使用POI生成Excel并導(dǎo)出

    java中使用POI生成Excel并導(dǎo)出

    注:本文章中代碼均為本地Demo版本,若后續(xù)代碼更新將不會更新文章 根據(jù)從數(shù)據(jù)庫查詢出的數(shù)據(jù),將其寫入excel表并導(dǎo)出 我的想法是通過在實體屬性上寫自定義注解的方式去完成。因為我們在代碼中可以通過反射的方式去獲取實體類中全部的注解及屬性名稱等等。我們可以

    2024年02月16日
    瀏覽(26)
  • 【Java】使用POI按模板樣式導(dǎo)出Excel

    根據(jù)模板樣式進行excel導(dǎo)出。 首先,當(dāng)然是要有一個excel模板,excel的樣式用wps等進行設(shè)置。 然后就是代碼的實現(xiàn)了,先引入POI的依賴: 然后就是實現(xiàn)方法里的代碼,首先定義響應(yīng)信息: 然后將excel模板轉(zhuǎn)為輸入流,這一步的實現(xiàn)方法有很多,具體選擇因人而異,我這里就舉

    2024年02月14日
    瀏覽(27)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包