91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

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

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

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

尚义县| 都安| 错那县| 蒙山县| 沂南县| 格尔木市| 桃园县| 舒城县| 扶沟县| 云南省| 宣城市| 玉龙| 天峨县| 米林县| 上林县| 句容市| 沙坪坝区| 清苑县| 类乌齐县| 讷河市| 浠水县| 紫阳县| 繁峙县| 新兴县| 云浮市| 小金县| 囊谦县| 巍山| 广安市| 门源| 阳春市| 黔江区| 舞阳县| 大足县| 阳山县| 廉江市| 海盐县| 高尔夫| 兴安县| 大宁县| 达州市|