mvc里如何上传excel然后将里面的数据导入到SQL数据库里

mvc里如何上传excel然后将里面的数据导入到SQL数据库里,第1张

我只有asp.net的,c#也可以使用,但是没测试过java那些的。将Excel里面的数据导入到数据库中的原理就是将Excel里面的数据存储到一个dataTable中,然后将数据一行一行添加到数据库的表里。给你部分代码,相信你能够如此好学,应该能看懂,有些变量你自己研究是什么,不然全部给你打出来了,你就只会copy了。

SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["aa"].ToString())

            con.Open()//数据库连接字符串

            DataTable dtXls = new DataTable()

            if (this.fudAdd.PostedFile.FileName.ToString().Trim() != "" && this.fudAdd.PostedFile.FileName!=null)

            {

                string filePath = this.fudAdd.PostedFile.FileName.ToString().Trim()

                FileInfo fileTag = new FileInfo(fudAdd.PostedFile.FileName)

                string extendedName = fileTag.Extension

                if (extendedName.ToLower() != ".xls" && extendedName.ToLower() != ".xlsx")

                {

                    Response.Write("<script>alert('请选择一个Excel文件!')</script>")

                    return

                }

                else

                {

                    dtXls = ExcelToDataTable(filePath,extendedName)

                    if (dtXls==null||dtXls.Rows.Count <= 0 || dtXls.Columns[0].ToString() == "")

                    {

                        Response.Write("<script>alert('请你确认上传的Excel中有资料!')</script>")

                        return

                    }

                    else

                    {

                        if (dtXls.Columns[0].ToString() != "手机号码" || dtXls.Columns[1].ToString() != "状态")

                        {

                            Response.Write("<script>alert('请确定Excel资料的格式为[手机号码][状态]!')</script>")

                            return

                        }

                        else

                        {

                            if (dtXls.Rows[0][0].ToString() == "")

                            {

                                Response.Write("<script>alert('请确定Excel资料的格式为[手机号码][状态]!')</script>")

                                return

                            }

                            else

                            {

                                string result = AddXlsData(dtXls, con)

                                string[] resultData = result.Split('-')

                                string msg = "资料上传成功!共计" + resultData[0] + "条成功," + resultData[1] + "条失败!"

                                Response.Write("<script>alert('" + msg + "')</script>")

                                logwrite.LogOpera(userid, "UnExistMobile_Mag.aspx", "UnExistMobile_Mag.aspx.cs", "成功上传一批空号")//记录log

                                BindData()

                                return

                            }

                        }

                    }

                }

                con.Close()

//

#region ExcelToDataTable

    /// <summary>

    /// 读取xls文件

  /// Add by

    /// </summary>

    /// <param name="fileName"></param>

    /// <returns></returns>

    protected DataTable ExcelToDataTable(string fileName, string extendedName)

    {

        string strConn = string.Empty

        if (extendedName.ToLower() == ".xls")

        {

            strConn = "Provider=Microsoft.Jet.OLEDB.4.0Data Source=" + fileName + "Extended Properties='Excel 8.0HDR=YesIMEX=1'"

        }

        if (extendedName.ToLower() == ".xlsx")

        {

            strConn = "Provider=Microsoft.ACE.OLEDB.12.0Data Source=" + fileName + "Extended Properties='Excel 12.0HDR=YES'"

        }

        OleDbConnection conn = new OleDbConnection(strConn)

        conn.Open()

        System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null)

        string tableName = schemaTable.Rows[0][2].ToString().Trim()

        string strExcel = ""

        OleDbDataAdapter myCommand = null

        DataSet ds = null

        strExcel = "Select   *   From   [" + tableName + "]"

        myCommand = new OleDbDataAdapter(strExcel, strConn)

        ds = new DataSet()

        myCommand.Fill(ds, tableName)

        if (ds != null)

        {

            System.Data.DataTable dt = ds.Tables[0]

            return dt

        }

        else

        {

            return null

        }

        conn.Close()

        ds.Dispose()

    }

    #endregion

一) 其实这个功能在spring2.x时代就提供了。一直没用过,今天在spring-mvc3.2.x的环境下试验了一次。还算简单易用。

二) 依赖。

spring依赖POI或jExcel来实现对excel输出的支持,前者是apache出品,貌似名气更大,本例使用第一个。

<dependency>

<groupId>org.apache.poi</groupId>

<artifactId>poi</artifactId>

<version>3.7</version>

</dependency>

三) spring提供了一个AbstractExcelView作为自己实现的视图的父类。实例代码如下。

package ying.car.view

import java.text.DateFormat

import java.text.SimpleDateFormat

import java.util.List

import java.util.Map

import javax.servlet.http.HttpServletRequest

import javax.servlet.http.HttpServletResponse

import org.apache.poi.hssf.usermodel.HSSFDataFormat

import org.apache.poi.hssf.usermodel.HSSFSheet

import org.apache.poi.hssf.usermodel.HSSFWorkbook

import org.apache.poi.ss.usermodel.Cell

import org.apache.poi.ss.usermodel.CellStyle

import org.apache.poi.ss.usermodel.IndexedColors

import org.joda.time.DateTime

import org.slf4j.Logger

import org.slf4j.LoggerFactory

import org.springframework.web.servlet.view.document.AbstractExcelView

import ying.car.binding.DateRange

import ying.car.domain.RefuelingRecord

public class RefuelingRecordExcelView extends AbstractExcelView {

private static final Logger LOGGER = LoggerFactory.getLogger(RefuelingRecordExcelView.class)

private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd")

@Override

@SuppressWarnings({"unchecked"})

protected void buildExcelDocument(

Map<String, Object> model,        // MVC中的M就在这里了

HSSFWorkbook workbook,

HttpServletRequest request,

HttpServletResponse response) throws Exception

{

("yyyy/MM/dd"))

LOGGER.debug("end: {}", new DateTime(dr.getEnd()).toString("yyyy/MM/dd"))

}

}

HSSFSheet sheet = workbook.createSheet(DATE_FORMAT.format(dr.getStart()) + "-" + DATE_FORMAT.format(dr.getEnd()))

setColumnsWidth(sheet)

fillTableHeader(workbook, sheet)

fillTableBody(workbook, sheet, rrl)

}

private void setColumnsWidth(HSSFSheet sheet) {

final int[] warr = new int[] {

500,  // <空>

4500, // 日期

4500, // 车辆

4500, // 燃油种类

4500, // 燃油单价

4500, // 加油方式

4500, // 加油量

3000, // 花费

12000  // 备注

}

for (int i = 0 i < warr.length i ++) {

sheet.setColumnWidth(i, warr[i])

}

}

// 填充表格头

private void fillTableHeader(HSSFWorkbook workbook, HSSFSheet sheet) {

final String[] contents = new String[] {

"日期",

"车辆",

"燃油种类",

"燃油单价(元/升)",

"加油方式",

"加油量(升)",

"花费(元)",

"备注"

}

int r = 1

int c = 1

CellStyle style = workbook.createCellStyle()

style.setFillForegroundColor(IndexedColors.YELLOW.getIndex())      // 填充黄色

style.setFillPattern(CellStyle.SOLID_FOREGROUND)           // 填充方式

// 设置border

style.setBorderLeft(CellStyle.BORDER_THIN)

style.setBorderRight(CellStyle.BORDER_THIN)

style.setBorderTop(CellStyle.BORDER_THIN)

style.setBorderBottom(CellStyle.BORDER_THIN)

for (int i = 0 i < contents.length i ++) {

Cell cell = getCell(sheet, r, c + i)

cell.setCellValue(contents[i])

cell.setCellStyle(style)

}

}

private void fillTableBody(HSSFWorkbook workbook, HSSFSheet sheet, List<RefuelingRecord> records) {

// 通用style

CellStyle style = workbook.createCellStyle()

style.setFillForegroundColor(IndexedColors.WHITE.getIndex())       // 填充白色

style.setFillPattern(CellStyle.SOLID_FOREGROUND)                   // 填充方式

style.setBorderLeft(CellStyle.BORDER_THIN)

style.setBorderRight(CellStyle.BORDER_THIN)

style.setBorderTop(CellStyle.BORDER_THIN)

style.setBorderBottom(CellStyle.BORDER_THIN)

// 日期style

CellStyle dateStyle = workbook.createCellStyle()

dateStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex())       // 填充白色

dateStyle.setFillPattern(CellStyle.SOLID_FOREGROUND)                   // 填充方式

dateStyle.setBorderLeft(CellStyle.BORDER_THIN)

dateStyle.setBorderRight(CellStyle.BORDER_THIN)

dateStyle.setBorderTop(CellStyle.BORDER_THIN)

dateStyle.setBorderBottom(CellStyle.BORDER_THIN)

dateStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"))

int r = 2

int c = 1

Cell cell = null

for (int i = 0 i < records.size() i ++) {

RefuelingRecord rr = records.get(i)

// 日期

cell = getCell(sheet, r, c + 0)

if (rr.getDate() != null)

cell.setCellValue(rr.getDate())

cell.setCellStyle(dateStyle)

// 车辆

cell = getCell(sheet, r, c + 1)

if (rr.getVehicle().getNickname() != null)

cell.setCellValue(rr.getVehicle().getNickname())

cell.setCellStyle(style)

// 燃油种类

cell = getCell(sheet, r, c + 2)

if (rr.getGasType() != null) {

String s = null

switch (rr.getGasType()) {

case _0: s  = "0号柴油" break

case _93: s = "93号汽油" break

case _97: s = "97号汽油" break

case _98: s = "98号汽油" break

}

cell.setCellValue(s)

}

cell.setCellStyle(style)

// 单价

cell = getCell(sheet, r, c + 3)

if (rr.getPriceOfGas() != null)

cell.setCellValue(rr.getPriceOfGas())

cell.setCellStyle(style)

// 加油方式

cell = getCell(sheet, r, c + 4)

if (rr.getRefuelingType() != null) {

String s = null

switch (rr.getRefuelingType()) {

case FIXED_CUBAGE:

s = "固定容积" break

case FIXED_MONEY:

s = "固定金额" break

case FULL:

s = "加满" break

}

cell.setCellValue(s)

}

cell.setCellStyle(style)

// 加油量

cell = getCell(sheet, r, c + 5)

if (rr.getCubageOfGas() != null)

cell.setCellValue(rr.getCubageOfGas())

cell.setCellStyle(style)

// 花费

cell = getCell(sheet, r, c + 6)

if (rr.getSumOfMoney() != null)

cell.setCellValue(rr.getSumOfMoney())

cell.setCellStyle(style)

// 备注

cell = getCell(sheet, r, c + 7)

if (rr.getComment() != null)

cell.setCellValue(rr.getComment())

cell.setCellStyle(style)

r ++

}

}

}

cell.setCellStyle(style)

// 燃油种类

cell = getCell(sheet, r, c + 2)

if (rr.getGasType() != null) {

String s = null

switch (rr.getGasType()) {

case _0: s  = "0号柴油"break

case _93: s = "93号汽油"break

case _97: s = "97号汽油"break

case _98: s = "98号汽油"break

}

cell.setCellValue(s)

}

cell.setCellStyle(style)

// 单价

cell = getCell(sheet, r, c + 3)

if (rr.getPriceOfGas() != null)

cell.setCellValue(rr.getPriceOfGas())

cell.setCellStyle(style)

// 加油方式

cell = getCell(sheet, r, c + 4)

if (rr.getRefuelingType() != null) {

String s = null

switch (rr.getRefuelingType()) {

case FIXED_CUBAGE:

s = "固定容积"break

case FIXED_MONEY:

s = "固定金额"break

case FULL:

s = "加满"break

}

cell.setCellValue(s)

}

cell.setCellStyle(style)

// 加油量

cell = getCell(sheet, r, c + 5)

if (rr.getCubageOfGas() != null)

cell.setCellValue(rr.getCubageOfGas())

cell.setCellStyle(style)

// 花费

cell = getCell(sheet, r, c + 6)

if (rr.getSumOfMoney() != null)

cell.setCellValue(rr.getSumOfMoney())

cell.setCellStyle(style)

// 备注

cell = getCell(sheet, r, c + 7)

if (rr.getComment() != null)

cell.setCellValue(rr.getComment())

cell.setCellStyle(style)

r ++

}

}

}

四) Controller中返回逻辑视图名 (代码片段)

Java代码

@RequiresUser       // 安全框架用元注释

@RequiresRoles({"ROLE_USER"})

@RequestMapping(value = "/list/excel", method = RequestMethod.GET)

public String listByExcel(

@DateRangeFormat(pattern = "yyyy-MM-dd") @RequestParam("dateRange") DateRange dateRange,

ModelMap modelMap

)

{

}

// 放入model

modelMap.put("dateRange", dateRange)

modelMap.put("refuelingRecordList", gasService.findRefuelingRecordByDateRange(currentUserId, dateRange))

return "refueling-record-list" // 最终返回逻辑视图名

}

五) 为spring-mvc配置多个视图解析器。

<bean class="org.springframework.web.servlet.view.XmlViewResolver">

<property name="order" value="1" /> <!-- order很重要 -->

<property name="location" value="classpath:/META-INF/views.xml" />

</bean>

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="order" value="9999" />

<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />

<property name="prefix" value="/WEB-INF/jsp/"/>

<property name="suffix" value=".jsp"/>

六) 效果图

首先将excel是不可能直接导入到表格中的,因为它是文件,easyui用的不多,不清楚有没有这个支持,但是如果用一般的方法,当然是用java第三方的解析excle的插件,来解析上传的excle,读取excle的内容,存入bean中,前台再显示。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/tougao/12089678.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-20
下一篇 2023-05-20

发表评论

登录后才能评论

评论列表(0条)

保存