Java實現(xiàn)Excel導入導出數(shù)據(jù)庫的方法示例
本文實例講述了Java實現(xiàn)Excel導入導出數(shù)據(jù)庫的方法。分享給大家供大家參考,具體如下:
由于公司需求,想通過Excel導入數(shù)據(jù)添加到數(shù)據(jù)庫中,而導入的Excel的字段是不固定的,使用得通過動態(tài)創(chuàng)建數(shù)據(jù)表,每個Excel對應一張數(shù)據(jù)表,怎么動態(tài)創(chuàng)建數(shù)據(jù)表,可以參考前面一篇《java使用JDBC動態(tài)創(chuàng)建數(shù)據(jù)表及SQL預處理的方法》。
下面主要講講怎么將Excel導入到數(shù)據(jù)庫中,直接上代碼:干貨走起~~
ExcellToObjectUtil 類
主要功能是講Excel中的數(shù)據(jù)導入到數(shù)據(jù)庫中,有幾個注意點就是
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文件內(nèi)容 * * @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>(); // 循環(huán)工作表Sheet for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) { HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet); if (hssfSheet == null) { continue; } // 循環(huán)行Row for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) { HSSFRow hssfRow = hssfSheet.getRow(rowNum); if (hssfRow == null) { continue; } exam = new ExamInfo(); // 循環(huán)列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>(); // 循環(huán)工作表Sheet for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) { HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet); if (hssfSheet == null) { continue; } // 循環(huán)行Row for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) { HSSFRow hssfRow = hssfSheet.getRow(rowNum); if (hssfRow == null) { continue; } exam = new ExamInfo(); // 循環(huán)列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)); //讀取結(jié)束時間 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) { // 返回數(shù)值類型的值 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 = {"序號","編號","真實姓名","證件類型","證件號","性別","出生年月","科目","準考證號","座位號","考場號","開考時間","結(jié)束時間"}; //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 { // 獲取總列數(shù) // int CountColumnNum = CountColumnNum; // 創(chuàng)建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++) { // 創(chuàng)建一行 HSSFRow row = sheet.createRow(i + 1); // 得到要插入的每一條記錄 xlsDto = xls.get(i); for (int colu = 0; colu <= 12; colu++) { // 在一行內(nèi)循環(huán) 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()); } } // 創(chuàng)建文件輸出流,準備輸出電子表格 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(); } }
導出的功能十分簡單,只要封裝好對象,直接調(diào)用方法即可,現(xiàn)在講講導入的時候前臺頁面怎么調(diào)用問題,
<form method="post" action="adminLogin/auditResults/import" enctype="multipart/form-data" onsubmit="return importData();"> <input id="filepath" name="insuranceExcelFile" type="file" size="30" value="" style="font-size:14px" /> <button type="submit" style="height:25px" value="導入數(shù)據(jù)">導入數(shù)據(jù)</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讀取需要的數(shù)據(jù) List<ExamInfo> list = ExcellToObjectUtil.readXlsForJS(poifsFileSystem); for (ExamInfo ei : list) { //通過匹配身份證號 填寫對應的數(shù)據(jù) for (ExamInfo in : info){ //如果身份證號 相同 則錄入數(shù)據(jù) 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; }
好了,Excel導入導出的功能都搞定了,簡單吧,需求自己修改一下 封裝的對象格式和設置Excel的每個列即可自己使用??!
更多關(guān)于java相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java操作Excel技巧總結(jié)》、《Java+MySQL數(shù)據(jù)庫程序設計總結(jié)》、《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java文件與目錄操作技巧匯總》及《Java操作DOM節(jié)點技巧總結(jié)》
希望本文所述對大家java程序設計有所幫助。
- Java實現(xiàn)從數(shù)據(jù)庫導出大量數(shù)據(jù)記錄并保存到文件的方法
- Java數(shù)據(jù)導出功能之導出Excel文件實例
- java導出數(shù)據(jù)庫的全部表到excel
- Java使用poi組件導出Excel格式數(shù)據(jù)
- Java使用easyExcel導出excel數(shù)據(jù)案例
- java從mysql導出數(shù)據(jù)的具體實例
- java web將數(shù)據(jù)導出為pdf格式文件代碼片段
- java實現(xiàn)異步導出數(shù)據(jù)
- Java樹形結(jié)構(gòu)數(shù)據(jù)生成導出excel文件方法記錄
- JAVA實現(xiàn)億級千萬級數(shù)據(jù)順序?qū)С龅氖纠a
相關(guān)文章
解決MyEclipse10.7部署報錯拋空指針異常問題的方法
這篇文章主要介紹了解決MyEclipse10.7部署報錯拋空指針異常問題的方法,需要的朋友可以參考下2015-12-12Springboot使用POI實現(xiàn)導出Excel文件示例
本篇文章主要介紹了Springboot使用POI實現(xiàn)導出Excel文件示例,非常具有實用價值,需要的朋友可以參考下。2017-02-02Java多線程中Thread.currentThread()和this的區(qū)別詳解
這篇文章主要介紹了Java多線程中Thread.currentThread()和this的區(qū)別詳解,Thread.currentThread()方法返回的是對當前正在執(zhí)行的線程對象的引用,this代表的是當前調(diào)用它所在函數(shù)所屬的對象的引用,需要的朋友可以參考下2023-08-08springboot+vue實現(xiàn)阿里云oss上傳的示例代碼
文件上傳是常用的功能,本文主要介紹了springboot+vue實現(xiàn)阿里云oss上傳的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2024-06-06Java實現(xiàn)List轉(zhuǎn)換為Map的方法小結(jié)
這篇文章主要為大家詳細介紹了Java實現(xiàn)List轉(zhuǎn)換為Map的一些常見的方法,文中的示例代碼講解詳細,具有一定的借鑒價值,有需要的小伙伴可以參考一下2024-03-03