<h2>这里是上传Excel功能页面</h2>
<div>
<form action="/Improve_Excel/get_Excel" method="post" enctype="multipart/form-data">//上传文件必须要设置enctype="multipart/form-data"!!!
<input type="file" id="" name="file" value="上传文件" />
<br />
<br />
<input type="submit" id="" name="" value="上传文件按钮" />
</form>
</div>
using Aspose.Cells;
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web;
using System.Web.Mvc;
namespace JJQ_Practice.Controllers
{
public class Improve_ExcelController : Controller
{
// GET: Improve_Excel
public ActionResult Index()
{
return View();
}
public ActionResult get_Excel()
{
/////////////////////////////////////////////////////////////////
//上传并保存文件
HttpPostedFileBase file = Request.Files["file"];
if (file == null || file.ContentLength <= 0)
{
return Content("请选择文件!");
}
Stream streamfile = file.InputStream;
string FinName = Path.GetExtension(file.FileName);//得到文件后缀名
if (FinName != ".xls" && FinName != ".xlsx")
{
return Content("只能上传Excel文档");
}
string file_path = Server.MapPath("file_centre");
var GUID = Guid.NewGuid();
if (!Directory.Exists(file_path))
{
Directory.CreateDirectory(file_path);
}
var file_Path_Url = Path.Combine(file_path, Path.GetFileName(file.FileName));
file.SaveAs(file_Path_Url);//上传后保存文件
////////////////////////////////////////////////////////////////
var dt = GetExcelData(file_Path_Url, 0);//得到第1个sheet表;index=0,1,2,3,...
Workbook book = new Workbook(file_Path_Url);
var all_sheet_Count = book.Worksheets.Count;//得到execl表中有几个sheet表,数量;;为以后(本实例中没有去实现)一execl多表写入做for循环准备
//!!!!!!!声明数据库中对应的表的表名;dbo.libraya表!!!!!!!重要!!!!!
var table1 = "aa";//!!!!!!!声明数据库中对应的表的表名(就是数据库中已经有的表,没有数据的表);dbo.aa表!!!!!!!重要!!!!!
BatchInsertBySqlBulkCopy(dt, table1);
return Content("写入成功!");
}
public static void BatchInsertBySqlBulkCopy(DataTable dt, string tableName)
{
var connString = "Data Source=*******;Initial Catalog=*******;User ID=*******;Password=*******;Min Pool Size=10;Max Pool Size=255;Connect Timeout=30";
using (SqlBulkCopy sbc = new SqlBulkCopy(connString))
{
sbc.BatchSize = dt.Rows.Count;
sbc.BulkCopyTimeout = 10;
sbc.DestinationTableName = tableName;
for (int i = 0; i < dt.Columns.Count; i++)
{
sbc.ColumnMappings.Add(dt.Columns[i].ColumnName, i);
}
//将dt表中的数据全部写入数据库中对应名为tableName的表中
sbc.WriteToServer(dt);
}
}
#region Excel组件:读取服务器端文件(配合导入用)
public DataTable GetExcelData(string strSysUrl, int pageInfo)
{
try
{
//解析插入数据库
Workbook book = new Workbook(strSysUrl);
Worksheet sheet = book.Worksheets[pageInfo];
Cells cells = sheet.Cells;
var num = book.Worksheets.Count;
//提取excel数据 转换为DataTable
DataTable dt = cells.ExportDataTableAsString(0, 0, cells.MaxDataRow + 1, cells.MaxDataColumn + 1, true);
return dt;
}
catch (Exception ex)
{
return null;
}
}
#endregion
}
}
原文:https://www.cnblogs.com/jsll/p/11671360.html