当前位置:首页 > 实用技巧 >

asp网页中如何导入excel(asp如何读取excel)

来源:原点资讯(www.yd166.com)时间:2023-10-27 08:46:19作者:YD166手机阅读>>

asp网页中如何导入excel,asp如何读取excel(1)

asp网页中如何导入excel,asp如何读取excel(2)

1、点击引用右键,管理NuGet程序包,输入NPIO,选择红框选中的下载

2、创建一个 ExcelController 控制器,将Index 方法生成视图

3、批量导入excel的页面源码:

<h2>批量导入excel</h2>

<div>

@using (Html.BeginForm("Import", "Excel", FormMethod.Post, new { enctype = "multipart/form-data" }))

{

<input name="files" type="file" multiple="multiple" id="=file" />

<br />

<br />

<input name="submit" id="submit" type="submit" value="批量导入" />

}

</div>

这里需要注意:file 的multiple属性是能多个文件选中,enctype = "multipart/form-data" 是上传必须的表单属性

4、在ExcelController 控制器里面添加方法

[HttpPost]

public ActionResult Import(IEnumerable<HttpPostedFileBase> files)

{

// var fileName = file.FileName;

var filePath = Server.MapPath(string.Format("~/{0}", "Files"));

foreach (var file in files)

{

if (file != null && file.ContentLength > 0)

{

var path = Path.Combine(filePath, file.FileName);

file.SaveAs(path);

DataTable excelTable = new DataTable();

excelTable = ImportExcel.GetExcelDataTable(path);

DataTable dbdata = new DataTable();

dbdata.Columns.Add("ids");

dbdata.Columns.Add("users");

dbdata.Columns.Add("area");

dbdata.Columns.Add("school");

dbdata.Columns.Add("classes");

dbdata.Columns.Add("name");

dbdata.Columns.Add("phone");

dbdata.Columns.Add("integration");

dbdata.Columns.Add("states");

dbdata.Columns.Add("createDate");

dbdata.Columns.Add("refreshDate");

for (int i = 0; i < excelTable.Rows.Count; i )

{

DataRow dr = excelTable.Rows[i];

DataRow dr_ = dbdata.NewRow();

dr_["ids"] = dr["ID"];

dr_["users"] = dr["用户"];

dr_["area"] = dr["区域"];

dr_["school"] = dr["学校"];

dr_["classes"] = dr["班级"];

dr_["name"] = dr["姓名"];

dr_["phone"] = dr["手机"];

dr_["integration"] = dr["积分"];

dr_["states"] = dr["状态"];

dr_["createDate"] = dr["创建时间"];

dr_["refreshDate"] = dr["更新时间"];

dbdata.Rows.Add(dr_);

}

RemoveEmpty(dbdata);

string constr = System.Configuration.ConfigurationManager.AppSettings["cool"];

SqlBulkCopyByDatatable(constr, "student", dbdata);

}

}

return RedirectToAction("Index", "DataRefsh");

}

/// <summary>

/// 大数据插入

/// </summary>

/// <param name="connectionString">目标库连接</param>

/// <param name="TableName">目标表</param>

/// <param name="dtSelect">来源数据</param>

public static void SqlBulkCopyByDatatable(string connectionString, string TableName, DataTable dtSelect)

{

using (SqlConnection conn = new SqlConnection(connectionString))

{

using (SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction))

{

try

{

sqlbulkcopy.DestinationTableName = TableName;

sqlbulkcopy.BatchSize = 20000;

sqlbulkcopy.BulkCopyTimeout = 0;//不限时间

for (int i = 0; i < dtSelect.Columns.Count; i )

{

sqlbulkcopy.ColumnMappings.Add(dtSelect.Columns[i].ColumnName, dtSelect.Columns[i].ColumnName);

}

sqlbulkcopy.WriteToServer(dtSelect);

}

catch (System.Exception ex)

{

throw ex;

}

}

}

}

protected void RemoveEmpty(DataTable dt)

{

List<DataRow> removelist = new List<DataRow>();

for (int i = 0; i < dt.Rows.Count; i )

{

bool IsNull = true;

for (int j = 0; j < dt.Columns.Count; j )

{

if (!string.IsNullOrEmpty(dt.Rows[i][j].ToString().Trim()))

{

IsNull = false;

}

}

if (IsNull)

{

removelist.Add(dt.Rows[i]);

}

}

for (int i = 0; i < removelist.Count; i )

{

dt.Rows.Remove(removelist[i]);

}

}

这里需要注意:IEnumerable<HttpPostedFileBase> 是读取多个文件的名称,HttpPostedFileBase只能读取一个,还有就是files 是file 控件name 相对应的

5、string constr = System.Configuration.ConfigurationManager.AppSettings["cool"]; 需要在web.config 里面的appSettings 里面添加数据库连接字符串的配置

asp网页中如何导入excel,asp如何读取excel(3)

6、控制器import 方法里面有用到GetExcelDataTable 和GetCellValue 方法

这里创建一个ImportExcel 类,创建以下两个方法

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using NPOI;

using System.Data;

using NPOI.SS.UserModel;

using NPOI.HSSF.UserModel;

using NPOI.XSSF.UserModel;

using System.IO;

namespace Cool{

public class ImportExcel

{

public static DataTable GetExcelDataTable(string filePath)

{

IWorkbook Workbook;

DataTable table = new DataTable();

try

{

using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))

{

//XSSFWorkbook 使用XLSX格式,HSSFWorkbook 使用XLS格式

string fileExt = Path.GetExtension(filePath).ToLower();

if (fileExt == ".xls")

{

Workbook = new HSSFWorkbook(fileStream);

}

else if (fileExt == ".xlsx")

{

Workbook = new XSSFWorkbook(fileStream);

}

else

{

Workbook = null;

}

}

}

catch (Exception ex)

{

throw ex;

}

//定位在第一个sheet

ISheet sheet = Workbook.GetSheetAt(0);

//第一行为标题行

IRow headerRow = sheet.GetRow(0);

int cellCount = headerRow.LastCellNum;

int rowCount = sheet.LastRowNum;

//循环添加标题列

for (int i = headerRow.FirstCellNum; i < cellCount; i )

{

DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);

table.Columns.Add(column);

}

//数据

for (int i = (sheet.FirstRowNum 1); i <= rowCount; i )

{

IRow row = sheet.GetRow(i);

DataRow dataRow = table.NewRow();

if (row != null)

{

for (int j = row.FirstCellNum; j < cellCount; j )

{

if (row.GetCell(j) != null)

{

dataRow[j] = GetCellValue(row.GetCell(j));

}

}

}

table.Rows.Add(dataRow);

}

return table;

}

private static string GetCellValue(ICell cell)

{

if (cell == null)

{

return string.Empty;

}

switch (cell.CellType)

{

case CellType.Blank:

return string.Empty;

case CellType.Boolean:

return cell.BooleanCellValue.ToString();

case CellType.Error:

return cell.ErrorCellValue.ToString();

case CellType.Numeric:

case CellType.Unknown:

default:

return cell.ToString();

case CellType.String:

return cell.StringCellValue;

case CellType.Formula:

try

{

HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(cell.Sheet.Workbook);

e.EvaluateInCell(cell);

return cell.ToString();

}

catch

{

return cell.NumericCellValue.ToString();

}

}

}

}}

这里需要注意:NPOI 只支持93-2007的offcie 的excel文件,如果是高版本的excel文件,需要降级,打开excel文件,另存为93-2007 的.xls 文件即可

这样就可以批量把文件数据导入到数据库中了!!!

栏目热文

asp读取数据库显示表格(asp数据库怎么显示列表)

asp读取数据库显示表格(asp数据库怎么显示列表)

ASP.NET MVC4数据库操作实例之前文章介绍了MVC4与Pure框架结合进行的网页设计过程中如何定义控制器、方法、...

2023-10-27 08:49:59查看全文 >>

asp修改excel数据(asp怎么读取excel文件)

asp修改excel数据(asp怎么读取excel文件)

在本文中,您将学习如何在ASP.NET MVC 应用程序中创建、读取和编辑 Excel 电子表格。为此,我们将创建一个由...

2023-10-27 09:20:41查看全文 >>

如何在asp中添加一个表格(asp怎么插入表)

如何在asp中添加一个表格(asp怎么插入表)

1. 前言报表打印通常是管理信息系统中的一个重要模块,而Excel凭借它功能强大、应用灵活、通用性强等的优势在报表打印中...

2023-10-27 08:38:59查看全文 >>

怎么用asp循环输出表格(asp导入电子表格的方法有哪些)

怎么用asp循环输出表格(asp导入电子表格的方法有哪些)

可能是将一个html 表格变成 Microsoft Excel 格式的最快方法。ContentType 属性通知浏览器数...

2023-10-27 09:00:41查看全文 >>

asp表格导出到excel(asp网页导出excel)

asp表格导出到excel(asp网页导出excel)

asp导出到excel方法一:---------------------------------------------...

2023-10-27 08:56:59查看全文 >>

asp导出数据到excel表格(asp怎么把网页数据导到excel)

asp导出数据到excel表格(asp怎么把网页数据导到excel)

在web应用程序开发时,或许你会遇到这样的需求,如何在 Asp.Net Core 中实现 excel 或者 word 的...

2023-10-27 08:58:22查看全文 >>

asp中的excel怎么导入sql(asp怎么把网页数据导到excel)

asp中的excel怎么导入sql(asp怎么把网页数据导到excel)

上一节主介绍了数据库内部表的格式设定及其注意事项,在最后向大家提供了2张图片,分别是存储导入数据的表的格式和存储数据...

2023-10-27 08:44:09查看全文 >>

asp数据库查询显示表格(asp怎么查询两个表数据)

asp数据库查询显示表格(asp怎么查询两个表数据)

这篇文章主要介绍了Asp.net管理信息系统中数据统计功能的实现方法,需要的朋友可以参考下数据统计是每个系统中必备的功能...

2023-10-27 09:10:11查看全文 >>

asp怎么把表单储存到数据库(asp表单保存按钮)

asp怎么把表单储存到数据库(asp表单保存按钮)

request.QueryString 和 Request.Form 命令用于从表单取回信息,比如用户的输入。用户输入R...

2023-10-27 09:00:28查看全文 >>

asp怎么显示两个表中的数据(asp两个表同时查询)

asp怎么显示两个表中的数据(asp两个表同时查询)

ASP.NET MVC4数据库操作实例之前文章介绍了MVC4与Pure框架结合进行的网页设计过程中如何定义控制器、方法、...

2023-10-27 09:09:51查看全文 >>

文档排行