前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C# 实现xlsx文件导入

C# 实现xlsx文件导入

作者头像
likepoems
发布2023-03-04 17:18:24
1.1K0
发布2023-03-04 17:18:24
举报
文章被收录于专栏:学习笔记分享

本文最后更新于 128 天前,其中的信息可能已经有所发展或是发生改变。

1、前台页面

代码语言:javascript
复制
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    #loading {
        position: fixed;
        top: 50%;
        transform: translate(-50%, -50%);
        left: 50%;
        opacity: .8;
        -ms-flex-pack: center !important;
        justify-content: center !important;
        display: none;
    }

    .spinner {
        display: inline-block;
        width: 2rem;
        height: 2rem;
        vertical-align: text-bottom;
        border: 0.25em solid currentColor;
        border-right-color: transparent;
        border-radius: 50%;
        -webkit-animation: spinner .75s linear infinite;
        animation: spinner .75s linear infinite;
    }

    @keyframes spinner {
        to {
            transform: rotate(360deg);
        }
    }
</style>

<body>
    <button type="button" onclick="$('#btn').click()">upload</button>
    <input type="file" style="display: none;" id="btn" />
    <div id="loading">
        <div class="spinner">
            <span></span>
        </div>
    </div>
</body>
<script src="./jquery-3.3.1.min.js"></script>
<script>
    $('#btn').change(function (e) {
        let formData = new FormData();
        formData.append('files', e.target.files[0]);
        formData.append('userId', 'xiaoming');
        $.ajax({
            type: 'POST',
            url: 'http://localhost:3000/api/upload',
            cache: false,
            data: formData,
            contentType: false, // 不设置数据类型
            processData: false, // 将数据转换成对象,不对数据做处理
            beforeSend: function (result) {
                // 数据加载前,显示loading    
                if (result.readyState == 0) {
                    $("body").attr("disabled", true);
                    $("body").css("opacity", '.5');
                    $("#loading").show();
                }
            },
            success: function (result) {
                console.log(result.Message);
            },
            complete: function (result) {
                // 数据加载后,隐藏loading 
                if (result.status == 200) {
                    $("body").attr("disabled", false);
                    $("body").css("opacity", '1');
                    $("#loading").hide();
                }
                $('#btn').val(''); // 文件导入完成后就清空
            },
            error: function (error) {
                console.log(error)
            }
        })
    })
</script>

</html>

2、后台接口设计

代码语言:javascript
复制
using Ascentn.Workflow.Base;
using Medalsoft.Workflow.Resource.CommonUtil;
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web;
using System.Web.Http;

namespace Medalsoft.Workflow.Resource.Controllers
{
    [RoutePrefix("api/upload")]
    public class UploadController : ApiController
    {
        string connstr = AgilePointUtil.CreateSQLConnectInstance(); //:获取数据库连接字符串
        /// <summary>
        /// 导入xlsx文件
        /// </summary>
        /// <returns></returns>
        [Route("ImportFile"), HttpPost]
        public ResultData ImportFile()
        {
            using (var w = new LimitedConcurrency())
            {
                string fileName = "";
                Stream fileStream = null;
                var request = System.Web.HttpContext.Current.Request;
                var formData = request.Form;
                string userName = formData["userId"];
                string clearOriginalTableSql = $@"TRUNCATE TABLE UserInfo";
                string nowTime = DateTime.Now.ToString("yyyyMMddHHmmss"); // 获取当前时间
                string createBackupTableSql = $@"SELECT * INTO UserInfobackup{nowTime} FROM UserInfo";
                HttpFileCollection files = HttpContext.Current.Request.Files;

                SqlHelper.ExecteNonQuery(connstr, CommandType.Text, createBackupTableSql, null); // 根据时间创建备份表
                SqlHelper.ExecteNonQuery(connstr, CommandType.Text, clearOriginalTableSql, null); // 清空原数据表

                SqlConnection myConnection = new SqlConnection(connstr);
                myConnection.Open();
                //启动一个事务
                SqlTransaction myTrans = myConnection.BeginTransaction();
                //为事务创建一个命令
                SqlCommand myCommand = new SqlCommand();
                myCommand.Connection = myConnection;
                myCommand.Transaction = myTrans;

                // 判断上传的是否是xlsx文件
                foreach (string key in files.AllKeys)
                {
                    HttpPostedFile file = files[key];
                    if (string.IsNullOrEmpty(file.FileName) == false)
                    {
                        fileName = file.FileName;
                        fileStream = file.InputStream;
                    }
                    else
                    {
                        return new ResultData { IsError = true, Message = "未获取到Excel数据" };
                    }
                }
                if (Path.GetExtension(fileName).ToLower() != ".xls" && Path.GetExtension(fileName).ToLower() != ".xlsx")
                {
                    return new ResultData { IsError = true, Message = "请上传excel文件" };
                }

                // 读取文件
                try
                {
                    // 获取导入的xlsx文件数据
                    DataTable data = ExcelHelper.ImportStream(fileStream, fileName);

                    foreach (DataRow itemRows in data.Rows)
                    {
                        // string description = itemRows.ItemArray[1].ToString();
                        // string description = itemRows["UserDescription"].ToString();
                        string description = HandleString(itemRows["UserDescription"].ToString());
                        string userSex = itemRows["UserSex"].ToString();
                        string userAge = itemRows["UserAge"].ToString();
                        if (StringIsEmpty(userName))
                        {
                            return new ResultData { IsError = true, Message = "UserName不能为空" };
                        }
                        if (StringIsEmpty(description))
                        {
                            return new ResultData { IsError = true, Message = "UserDescription不能为空" };
                        }
                        if (StringIsEmpty(userSex))
                        {
                            return new ResultData { IsError = true, Message = "UserSex不能为空" };
                        }
                        if (!IsNumber(userAge))
                        {
                            return new ResultData { IsError = true, Message = "UserAge不是数字类型" };
                        }
                        string sql = $@"INSERT INTO UserInfo(
                                                    [ID],
                                                    [CREATED_DATE],
                                                    [UserName],
                                                    [UserSex],
                                                    [UserAge]
                                                    [UserDescription] VALUES (
                                                    NEWID(),
                                                    GETDATE(),
                                                    '{userName}',
                                                    '{userSex}',
                                                    '{userAge}', 
                                                    '{description}')";

                        myCommand.CommandText = sql;
                        myCommand.ExecuteNonQuery();
                        // SqlHelper.ExecteNonQuery(connstr, CommandType.Text, sql, null);

                    }

                    myTrans.Commit();
                    return new ResultData { IsError = false, Message = "数据导入成功" };
                }
                catch (Exception ex)
                {
                    myTrans.Rollback();  //遇到错误回滚
                    throw ex;
                }

            }

        }

        // 判断字符串
        public  bool StringIsEmpty(string str)
        {
            if (string.IsNullOrEmpty(str)) // 是空的返回true否则返回false
            {
                return true;
            }
            return false;
        }

        // 判断数字
        public  bool IsNumber(string number)  // 是数字返回true否则返回false
        {
            decimal num = 0;
            bool n = decimal.TryParse(number, out num);
            if (!string.IsNullOrEmpty(number) && n)
            {
                return true;
            }
            return false;
        }

        public string HandleString(string content)
        {
            if (content.Contains("'"))
            {
                content = content.Replace("'", "''");
            }
            return content;
        }

        public class ResultData
        {
            public bool IsError { get; set; }
            public string Message { get; set; }
        }
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-6-13 1,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1、前台页面
  • 2、后台接口设计
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档