GridView读取Excel文件的相关操作

一、应用背景:

  工作中经常会碰到导出Excel的情况,当然也同样会碰到读取Excel文件的时候,我们经常会遇到类似这样的需求:客户为了维护数据库方便经常把做好的Excel直接导入数据库(当然这个过程可能比我接下来做的要复杂的多),或者是用从数据库查出的一些数据和读取的Excel表格中的数据进行比较并找出不同的数据(数据核查)等等操作,这个时候我们就必须读取Excel文件。

二、代码:

  说明会在代码里进行。

  1. 前台:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ReadExcel.aspx.cs" Inherits="GridView经典应用.Pages.ReadExcel" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%-- 文件上传控件 用于将要读取的文件上传 并通过此控件获取文件的信息--%>
<asp:FileUpload ID="fileSelect" runat="server" />
<%-- 点击此按钮执行读取方法--%>
<asp:Button ID="btnRead" runat="server" Text="ReadStart"
onclick
="btnRead_Click" />
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>

  2. 后台:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;
using System.IO;

namespace GridView经典应用.Pages
{
public partial class ReadExcel : System.Web.UI.Page
{
string currFilePath = string.Empty; //待读取文件的全路径
string currFileExtension = string.Empty; //文件的扩展名
protected void Page_Load(object sender, EventArgs e)
{

}

protected void btnRead_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string returnString = string.Empty;
returnString = Upload();
if (returnString!=string.Empty )
{
Response.Write("<script>alert('" + returnString + "')</script>");
return;
}

if (this.currFileExtension == ".xlsx" || this.currFileExtension == ".xls")
{
dt = ReadExcelToTable(currFilePath); //读取Excel文件(.xls和.xlsx格式)
}
else if (this.currFileExtension == ".csv")
{
dt = ReadExcelWithStream(currFilePath); //读取.csv格式文件
}

this.GridView1.DataSource = dt;
this.GridView1.DataBind();

//如果该文件仅仅用于导入数据库,或是和数据库中的某个表的数据进行匹配核查,可以在此将文件删除
if (File.Exists(currFilePath))
{
File.Delete(currFilePath);
}
}

private string Upload()
{
string msg = string.Empty;
HttpPostedFile file = this.fileSelect.PostedFile;
string fileName = file.FileName;
string tempPath = System.IO.Path.GetTempPath(); //获取系统临时文件路径
fileName = System.IO.Path.GetFileName(fileName); //获取文件名(不带路径)
this.currFileExtension = System.IO.Path.GetExtension(fileName); //获取文件的扩展名
this.currFilePath = tempPath + fileName; //获取上传后的文件路径 记录到前面声明的全局变量
if (fileName == string.Empty)
{
msg = "路径不正确!";
}
else
{
file.SaveAs(this.currFilePath); //上传(此时文件已经上传到了服务器)
}
return msg;
}

///<summary>
///读取xls\xlsx格式的Excel文件的方法
///</ummary>
///<param name="path">待读取Excel的全路径</param>
///<returns></returns>

private DataTable ReadExcelToTable(string path)
{
//连接字符串
string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";
// Office 07及以上版本 不能出现多余的空格 而且分号注意//
using(OleDbConnection conn = new OleDbConnection(connstring))
{
conn.Open();
DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,new object[]{null,null,null,"Table"}); //得到所有sheet的名字
string firstSheetName = sheetsName.Rows[0][2].ToString(); //得到第一个sheet的名字
string sql = string.Format("SELECT * FROM [{0}]",firstSheetName); //查询字符串
OleDbDataAdapter ada =new OleDbDataAdapter(sql,connstring);
DataSet set = new DataSet();
ada.Fill(set);

return set.Tables[0];

}
}
///<summary>
///读取csv格式的Excel文件的方法
///</ummary>
///<param name="path">待读取Excel的全路径</param>
///<returns></returns>

private DataTable ReadExcelWithStream(string path)
{
DataTable dt = new DataTable();
bool isDtHasColumn = false; //标记DataTable 是否已经生成了列
StreamReader reader = new StreamReader(path,System.Text.Encoding.Default); //数据流
while(!reader.EndOfStream)
{
string mesage = reader.ReadLine();
string[] splitResult = mesage.Split(new char[]{','}, StringSplitOptions.None); //读取一行 以逗号分隔 存入数组
DataRow row = dt.NewRow();
for(int i = 0;i<splitResult.Length;i++)
{
if(!isDtHasColumn) //如果还没有生成列
{
dt.Columns.Add("column" + i,typeof(string));
}
row[i] = splitResult[i];
}
dt.Rows.Add(row); //添加行
isDtHasColumn = true; //读取第一行后 就标记已经存在列 再读取以后的行时,就不再生成列
}
return dt;
}
}
}

  这里我仅仅是做了功能实现,有很大的完善空间,大家可以自我发挥,希望有帮助

转载于:https://www.cnblogs.com/lihaibo/archive/2011/10/15/2212874.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值