1. 程式人生 > >使用POI將資料匯入匯出資料庫。

使用POI將資料匯入匯出資料庫。

POI將資料匯入匯出資料庫。(採用ssm框架)
1.前臺列表的展示
<script type="text/javascript">

    //進行資料的全選
    function selectAll(){
        var ids=document.getElementsByName("id");
        for(var i=0;i<ids.length;i++){
            ids[i].checked=!ids[i].checked;
        }
    }

    function downLoad(){
        var
ids=document.getElementsByName("id"); var id=""; for(var i=0;i<ids.length;i++){ id+=ids[i].value+"," } id=id.substring(0, id.length-1); if(confirm("確認下載嗎?")){ location.href="importExcel.action?ids="+id; } }
</script
>
</head> <body> <table border="1"> <tr> <th><input type="button" value="下載" onclick="downLoad()"></th> <th> <form action="importMySql.action" enctype="multipart/form-data" method="post"> <input type
="file" name="uploadFile" id="uploadFile"/>
<input type="submit" value="上傳"/> <input type="reset" value="重置"/> </form> </th> </tr> <tr> <th><input type="checkbox" onclick="selectAll()">全選</th> <th>ID</th> <th>姓名</th> <th>性別</th> </tr> <c:forEach items="${studentList}" var="stu"> <tr> <td><input type="checkbox" name="id" value="${stu.id}"></td> <td>${stu.id}</td> <td>${stu.name}</td> <td>${stu.sex}</td> </tr> </c:forEach> </table> </body>

這裡寫圖片描述


/**
     * @description:將資料庫中的資料匯出到excel
     * @author yaoxiaogang
     * @time 2016年6月20日
     */
    @RequestMapping("importExcel")
    public void ExportExcel(HttpServletResponse response,String ids) throws IOException{

        response.setContentType("application/vnd.ms-excel");
        //傳遞中文引數編碼
        String codedFileName = java.net.URLEncoder.encode("中文","UTF-8");
        response.setHeader("content-disposition", ";filename=" + codedFileName + ".xls");

        List<Student> list = new ArrayList<Student>();

        //前臺獲取的資料ids
        String[] array = ids.split(",");

        for (int i = 0; i < array.length; i++) {
            Student stu = studentService.findById(Integer.valueOf(array[i]));
            list.add(stu);
        }

        //定義一個工作薄
        Workbook workbook = new HSSFWorkbook();
        // 建立一個sheet頁
        Sheet sheet = workbook.createSheet("學生資訊");
        // 建立一行
        Row row = sheet.createRow(0);
        // 在本行賦值以0開始
        row.createCell(0).setCellValue("學號");
        row.createCell(1).setCellValue("姓名");
        row.createCell(2).setCellValue("性別");
        //excel格式
        CellStyle cellStyle = workbook.createCellStyle();
        // 格式化日期
        cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));
        //遍歷輸出
        for (int i = 0; i <  list.size(); i++) {
            Student stu = list.get(i);
            row = sheet.createRow(i);
            row.createCell(0).setCellValue(stu.getId());
            row.createCell(1).setCellValue(stu.getName());
            row.createCell(2).setCellValue(stu.getSex());
        }
        OutputStream  out = response.getOutputStream();  
        workbook.write(out); 
        out.flush();  
        out.close(); 
    }

2.點選下載以後,資料庫中的資料就匯出到Excel表中。

這裡寫圖片描述

3.在Excel表中多新增幾條資料,將Excel表中的資料匯入到資料庫中。

這裡寫圖片描述

/**
     * @description 將excel表中的資料匯入到資料庫中
     * @author yaoxiaogang
     * @time 2016年6月20日
     */
    @RequestMapping("importMySql")
    public String importMySql(@RequestParam MultipartFile uploadFile,HttpServletRequest request) throws IOException{
        //檔案上傳工具類
        UploadPicture upload = new UploadPicture();
        //獲得上傳檔案
        File target = upload.upLoadFile(uploadFile, request);

        List <Student> slist = new ArrayList<Student>();

        excelFile = new FileInputStream(target);
        // 將上傳的檔案放入到工作薄中
        Workbook wb = new HSSFWorkbook(excelFile);
        // 獲取sheet頁
        Sheet sheetAt = wb.getSheetAt(0);
        // 獲取行數
        int rowNum = sheetAt.getLastRowNum() + 1;

        for(int i=0;i<rowNum;i++){
            Student student = new Student();
            Row row = sheetAt.getRow(i);
            int lastCellNum = row.getLastCellNum();
            for(int j = 0;j < lastCellNum; j++){
                Cell cell = row.getCell(j);
                String cellValue = null;
                switch (cell.getCellType()) {
                case 0:
                    // 判斷excel單元格內容的格式,並對其進行轉換,轉換成資料庫裡所儲存的型別
                    cellValue = String.valueOf((int)cell.getNumericCellValue());
                    break;
                case 1:
                    cellValue = cell.getStringCellValue();
                    break;
                case 2:
                    cellValue = cell.getStringCellValue();
                    break;
                }

                switch (j) {
                case 1:
                    student.setName(cellValue);
                    break;

                case 2:
                    student.setSex(cellValue);
                    break;
            }
        }
            slist.add(student);
      }

      //往資料庫中迴圈加入資料
      for (Student stu : slist) {
        studentService.insert(stu);
      }
        return "redirect:list.controller";
    }

此時資料庫中就會多幾條資料。

這裡寫圖片描述

注意:在進行匯入資料庫時,需要一個檔案上傳工具類。

package com.baidu.dto;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;
/**
 * @author yaoxiaogang
 * @description 檔案上傳工具類
 * @time 下午6:33:25 2016年6月20日
 */
public class UploadPicture {

    public File  upLoadFile(MultipartFile uploadFile,HttpServletRequest request) throws IOException{
        String img=null;
        MultipartFile file = uploadFile;
        @SuppressWarnings("unused")
        String uploadFileName = file.getOriginalFilename();

        InputStream isRef = file.getInputStream();

        String targetDir = request.getSession().getServletContext()
                .getRealPath("/upload");

        SimpleDateFormat sdf=new SimpleDateFormat("yyyyy_MM_dd_hh_mm_ss");
        String getDateString=sdf.format(new Date());
        String newFileName=""+getDateString+System.nanoTime();
        File targetFile = new File(targetDir,newFileName);
        FileOutputStream fosRef = new FileOutputStream(targetFile);
        IOUtils.copy(isRef, fosRef);

        return targetFile;
    }


}

//資料的匯入匯出就成功了!!

快捷鍵

  • 加粗 Ctrl + B
  • 斜體 Ctrl + I
  • 引用 Ctrl + Q
  • 插入連結 Ctrl + L
  • 插入程式碼 Ctrl + K
  • 插入圖片 Ctrl + G
  • 提升標題 Ctrl + H
  • 有序列表 Ctrl + O
  • 無序列表 Ctrl + U
  • 橫線 Ctrl + R
  • 撤銷 Ctrl + Z
  • 重做 Ctrl + Y

Markdown及擴充套件

Markdown 是一種輕量級標記語言,它允許人們使用易讀易寫的純文字格式編寫文件,然後轉換成格式豐富的HTML頁面。 —— [ 維基百科 ]

使用簡單的符號標識不同的標題,將某些文字標記為粗體或者斜體,建立一個連結等,詳細語法參考幫助?。

本編輯器支援 Markdown Extra ,  擴充套件了很多好用的功能。具體請參考Github.

表格

Markdown Extra 表格語法:

專案 價格
Computer $1600
Phone $12
Pipe $1

可以使用冒號來定義對齊方式:

專案 價格 數量
Computer 1600 元 5
Phone 12 元 12
Pipe 1 元 234

定義列表

Markdown Extra 定義列表語法:
專案1
專案2
定義 A
定義 B
專案3
定義 C

定義 D

定義D內容

程式碼塊

程式碼塊語法遵循標準markdown程式碼,例如:

@requires_authorization
def somefunc(param1='', param2=0):
    '''A docstring'''
    if param1 > param2: # interesting
        print 'Greater'
    return (param2 - param1 + 1) or None
class SomeClass:
    pass
>>> message = '''interpreter
... prompt'''

腳註

生成一個腳註1.

目錄

[TOC]來生成目錄:

數學公式

使用MathJax渲染LaTex 數學公式,詳見math.stackexchange.com.

  • 行內公式,數學公式為: Γ(n)=(n1)!nN
  • 塊級公式:

x=b±b24ac2a

更多LaTex語法請參考 這兒.

UML 圖:

可以渲染序列圖:

或者流程圖:

  • 關於 序列圖 語法,參考 這兒,
  • 關於 流程圖 語法,參考 這兒.

離線寫部落格

即使使用者在沒有網路的情況下,也可以通過本編輯器離線寫部落格(直接在曾經使用過的瀏覽器中輸入write.blog.csdn.net/mdeditor即可。Markdown編輯器使用瀏覽器離線儲存將內容儲存在本地。

使用者寫部落格的過程中,內容實時儲存在瀏覽器快取中,在使用者關閉瀏覽器或者其它異常情況下,內容不會丟失。使用者再次開啟瀏覽器時,會顯示上次使用者正在編輯的沒有發表的內容。

部落格發表後,本地快取將被刪除。 

使用者可以選擇 把正在寫的部落格儲存到伺服器草稿箱,即使換瀏覽器或者清除快取,內容也不會丟失。

注意:雖然瀏覽器儲存大部分時候都比較可靠,但為了您的資料安全,在聯網後,請務必及時發表或者儲存到伺服器草稿箱

瀏覽器相容

  1. 目前,本編輯器對Chrome瀏覽器支援最為完整。建議大家使用較新版本的Chrome。
  2. IE9以下不支援
  3. IE9,10,11存在以下問題
    1. 不支援離線功能
    2. IE9不支援檔案匯入匯出
    3. IE10不支援拖拽檔案匯入


  1. 這裡是 腳註內容.