中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Java項目中如何將Excel文件從數據庫導入與導出

發布時間:2020-12-02 16:19:46 來源:億速云 閱讀:271 作者:Leah 欄目:編程語言

本篇文章給大家分享的是有關Java項目中如何將Excel文件從數據庫導入與導出,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

ExcellToObjectUtil 類

主要功能是講Excel中的數據導入到數據庫中,有幾個注意點就是

1.一般Excel中第一行是字段名稱,不需要導入,所以從第二行開始計算

2.每列的匹配要和對象的屬性一樣

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import com.forenms.exam.domain.ExamInfo;
public class ExcellToObjectUtil {
  //examId,realName,身份證,user_card,sex,沒有字段,assessment_project,admission_number,seat_number
   /**
   * 讀取xls文件內容
   * 
   * @return List<XlsDto>對象
   * @throws IOException
   *       輸入/輸出(i/o)異常
   */
  public static List<ExamInfo> readXls(POIFSFileSystem poifsFileSystem) throws IOException {
//    InputStream is = new FileInputStream(filepath);
    HSSFWorkbook hssfWorkbook = new HSSFWorkbook(poifsFileSystem);
    ExamInfo exam = null;
    List<ExamInfo> list = new ArrayList<ExamInfo>();
    // 循環工作表Sheet
    for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
      HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
      if (hssfSheet == null) {
        continue;
      }
      // 循環行Row
      for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
        HSSFRow hssfRow = hssfSheet.getRow(rowNum);
        if (hssfRow == null) {
          continue;
        }
        exam = new ExamInfo();
        // 循環列Cell
        HSSFCell examId = hssfRow.getCell(1);
        if (examId == null) {
          continue;
        }
        double id = Double.parseDouble(getValue(examId));
        exam.setExamId((int)id);
//        HSSFCell realName = hssfRow.getCell(2);
//        if (realName == null) {
//          continue;
//        }
//        exam.setRealName(getValue(realName));
//        HSSFCell userCard = hssfRow.getCell(4);
//        if (userCard == null) {
//          continue;
//        }
//        
//        exam.setUserCard(getValue(userCard));
        HSSFCell admission_number = hssfRow.getCell(8);
        if (admission_number == null) {
          continue;
        }
        exam.setAdmission_number(getValue(admission_number));
        HSSFCell seat_number = hssfRow.getCell(9);
        if (seat_number == null) {
          continue;
        }
        exam.setSeat_number(getValue(seat_number));
        list.add(exam);
      }
    }
    return list;
  }
  public static List<ExamInfo> readXlsForJS(POIFSFileSystem poifsFileSystem) throws IOException {
//   InputStream is = new FileInputStream(filepath);
   HSSFWorkbook hssfWorkbook = new HSSFWorkbook(poifsFileSystem);
   ExamInfo exam = null;
   List<ExamInfo> list = new ArrayList<ExamInfo>();
   // 循環工作表Sheet
   for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
     HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
     if (hssfSheet == null) {
       continue;
     }
     // 循環行Row
     for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
       HSSFRow hssfRow = hssfSheet.getRow(rowNum);
       if (hssfRow == null) {
         continue;
       }
       exam = new ExamInfo();
       // 循環列Cell 準考證號
       HSSFCell admission_number = hssfRow.getCell(0);
       if (admission_number == null) {
         continue;
       }
       exam.setAdmission_number(getValue(admission_number));
       //讀取身份證號
       HSSFCell userCard= hssfRow.getCell(2);
       if (userCard == null) {
        continue;
       }
       exam.setUserCard(getValue(userCard));
       //讀取座位號
       HSSFCell seat_number = hssfRow.getCell(3);
       if (seat_number == null) {
        continue;
       }
       exam.setSeat_number(getValue(seat_number));
       //讀取考場號
       HSSFCell fRoomName = hssfRow.getCell(6);
       if (fRoomName == null) {
        continue;
       }
       exam.setfRoomName(getValue(fRoomName));
       //讀取開考時間
       HSSFCell fBeginTime = hssfRow.getCell(8);
       if (fBeginTime == null) {
        continue;
       }
       exam.setfBeginTime(getValue(fBeginTime));
       //讀取結束時間
       HSSFCell fEndTime = hssfRow.getCell(9);
       if (fEndTime == null) {
        continue;
       }
       exam.setfEndTime(getValue(fEndTime));
       list.add(exam);
     }
   }
   return list;
 }
  /**
   * 得到Excel表中的值
   * 
   * @param hssfCell
   *      Excel中的每一個格子
   * @return Excel中每一個格子中的值
   */
  private static String getValue(HSSFCell hssfCell) {
    if (hssfCell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {
      // 返回布爾類型的值
      return String.valueOf(hssfCell.getBooleanCellValue());
    } else if (hssfCell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
      // 返回數值類型的值
      DecimalFormat df = new DecimalFormat("0"); 
      String strCell = df.format(hssfCell.getNumericCellValue());
      return String.valueOf(strCell);
    } else {
      // 返回字符串類型的值
      return String.valueOf(hssfCell.getStringCellValue());
    }
  }
}

當然有導入功能,一定也有導出功能,下面介紹導出功能,直接上代碼:

import java.io.OutputStream;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import com.forenms.exam.domain.ExamInfo;
public class ObjectToExcellUtil {
  //導出的文件名稱
  public static String FILE_NAME = "examInfo";
  public static String[] CELLS = {"序號","編號","真實姓名","證件類型","證件號","性別","出生年月","科目","準考證號","座位號","考場號","開考時間","結束時間"};
  //examId,realName,身份證,user_card,sex,沒有字段,assessment_project,admission_number,seat_number
  public static void examInfoToExcel(List<ExamInfo> xls,int CountColumnNum,String filename,String[] names,HttpServletResponse response) throws Exception {
      // 獲取總列數
//     int CountColumnNum = CountColumnNum;
      // 創建Excel文檔
      HSSFWorkbook hwb = new HSSFWorkbook();
      ExamInfo xlsDto = null;
      // sheet 對應一個工作頁
      HSSFSheet sheet = hwb.createSheet(filename);
//     sheet.setColumnHidden(1,true);//隱藏列
      HSSFRow firstrow = sheet.createRow(0); // 下標為0的行開始
      HSSFCell[] firstcell = new HSSFCell[names.length];
      for (int j = 0; j < names.length; j++) {
         sheet.setColumnWidth(j, 5000);
        firstcell[j] = firstrow.createCell(j);
        firstcell[j].setCellValue(new HSSFRichTextString(names[j]));
      }
      for (int i = 0; i < CountColumnNum; i++) {
        // 創建一行
        HSSFRow row = sheet.createRow(i + 1);
        // 得到要插入的每一條記錄
        xlsDto = xls.get(i);
        for (int colu = 0; colu <= 12; colu++) {
          // 在一行內循環
          HSSFCell xh = row.createCell(0);
          xh.setCellValue(i+1);
          HSSFCell examid = row.createCell(1);
          examid.setCellValue(xlsDto.getExamId());
          HSSFCell realName = row.createCell(2);
          realName.setCellValue(xlsDto.getRealName());
          HSSFCell zjlx = row.createCell(3);
          zjlx.setCellValue("身份證");
          HSSFCell userCard = row.createCell(4);
          userCard.setCellValue(xlsDto.getUserCard());
          HSSFCell sex = row.createCell(5);
          sex.setCellValue(xlsDto.getSex());
          HSSFCell born = row.createCell(6);
          String bornTime = xlsDto.getUserCard().substring(6, 14);
          born.setCellValue(bornTime);
          HSSFCell assessment_project = row.createCell(7);
          assessment_project.setCellValue(xlsDto.getAssessmentProject());
          HSSFCell admission_number = row.createCell(8);
          admission_number.setCellValue(xlsDto.getAdmission_number());
          HSSFCell seat_number = row.createCell(9);
          seat_number.setCellValue(xlsDto.getSeat_number());
          HSSFCell fRoomName = row.createCell(10);
          fRoomName.setCellValue(xlsDto.getfRoomName());
          HSSFCell fBeginTime = row.createCell(11);
          fBeginTime.setCellValue(xlsDto.getfBeginTime());
          HSSFCell fEndTime = row.createCell(12);
          fEndTime.setCellValue(xlsDto.getfEndTime());
        }
      }
      // 創建文件輸出流,準備輸出電子表格
      response.reset();
      response.setContentType("application/vnd.ms-excel;charset=GBK");
      response.addHeader("Content-Disposition", "attachment;filename="+filename+".xls");
      OutputStream os = response.getOutputStream(); 
      hwb.write(os);
      os.close();
    }
}

導出的功能十分簡單,只要封裝好對象,直接調用方法即可,現在講講導入的時候前臺頁面怎么調用問題,

<form method="post" action="adminLogin/auditResults/import" enctype="multipart/form-data" onsubmit="return importData();"> 
<input id="filepath" name="insuranceExcelFile" type="file" size="30" value=""   />
<button type="submit"  value="導入數據">導入數據</button>

導入的前臺表單提交的時候,要注意設置 enctype=”multipart/form-data” ,其他也沒什么難度。
后臺接受的controller:

/**
* 讀取用戶提供的examinfo.xls
* @param request
* @param response
* @param session
* @return
* @throws Exception
*/
@RequestMapping(value="adminLogin/auditResults/import",method=RequestMethod.POST)
public ModelAndView importExamInfoExcell(HttpServletRequest request,HttpServletResponse response, HttpSession session)throws Exception{
    //獲取請求封裝
    MultipartHttpServletRequest multipartRequest=(MultipartHttpServletRequest)request;
    Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
    //讀取需要填寫準考證號的人員名單
    ExamInfo examInfo = new ExamInfo();
    List<ExamInfo> info = examInfoService.queryExamInfoForDownLoad(examInfo);
    //獲取請求封裝對象
    for(Entry<String, MultipartFile> entry: fileMap.entrySet()){
      MultipartFile multipartFile = entry.getValue();
      InputStream inputStream = multipartFile.getInputStream();
      POIFSFileSystem poifsFileSystem = new POIFSFileSystem(inputStream);
      //從xml讀取需要的數據
      List<ExamInfo> list = ExcellToObjectUtil.readXlsForJS(poifsFileSystem);
      for (ExamInfo ei : list) {
         //通過匹配身份證號 填寫對應的數據
        for (ExamInfo in : info){
          //如果身份證號 相同 則錄入數據
if(in.getUserCard().trim().toUpperCase().equals(ei.getUserCard().trim().toUpperCase())){
            ei.setExamId(in.getExamId());
            examInfoService.updateExamInfoById(ei);
            break;
          }
        }
      }
    }
    ModelAndView mav=new ModelAndView(PATH+"importExcelTip");
    request.setAttribute("data", "ok");
    return mav;
}

以上就是Java項目中如何將Excel文件從數據庫導入與導出,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業資訊頻道。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

进贤县| 平利县| 宁化县| 嘉祥县| 寿阳县| 谢通门县| 深泽县| 南汇区| 新野县| 华安县| 安徽省| 海门市| 泌阳县| 曲周县| 无棣县| 定襄县| 宣城市| 永福县| 沙洋县| 海晏县| 宝鸡市| 绍兴市| 邮箱| 申扎县| 平潭县| 吉木乃县| 波密县| 陵川县| 旌德县| 永胜县| 华宁县| 神池县| 龙山县| 大邑县| 收藏| 邹平县| 祥云县| 莱芜市| 顺昌县| 麻栗坡县| 汕头市|