.Net读取Excel 返回DataTable实例代码

代码如下:

using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Collections;
using System.Data.OleDb;
using NuctechProject.DTO.Bll;
using System.Collections.Generic;
namespace NuctechProject.Layouts.Project
{
    public partial class IntroductionPlan : LayoutsPageBase
    {
        string url = Common.rootUrl;
        private string _strConn; //导入excel时的连接
        string pmurl = Common.proUrl;
        private UserBLL bll = new UserBLL();
        protected void Page_Load(object sender, EventArgs e)
        {
            hidProid.Value = Request.QueryString["proid"];
        }
        protected void BtnOK_Click(object sender, EventArgs e)
        {
            DataTable excelTable = null;

SPSecurity.RunWithElevatedPrivileges(delegate
            {
                if (BaseInfoTemplateFile.HasFile)
                {
                    List<string> noInput = new List<string>();
                    string strLoginName = HttpContext.Current.User.Identity.Name; //获取用户名
                    string folderTemp = strLoginName.Substring(strLoginName.LastIndexOf('\\') + 1);
                    try
                    {
                        string extension = Path.GetExtension(BaseInfoTemplateFile.FileName); //获取文件的后缀
                        if (extension != null)
                        {
                            string fileException = extension.ToLower();
                            if (fileException == ".xlsx" || fileException == ".xls")
                            {
                                #region 读取Excel
                                string fileFolder = Server.MapPath("~/_layouts/15/images/" + folderTemp + "Upfile/");
                                if (!Directory.Exists(fileFolder)) //根目录
                                {
                                    Directory.CreateDirectory(fileFolder); //判断上传目录是否存在     自动创建
                                }
                                BaseInfoTemplateFile.SaveAs(Server.MapPath("~/_layouts/15/images/" + folderTemp + "Upfile/" + BaseInfoTemplateFile.FileName));
                                string strFilepathNmae = Server.MapPath("~/_layouts/15/images/" + folderTemp + "Upfile/" + BaseInfoTemplateFile.FileName);
                                string strExcel = ExcelSheetName(strFilepathNmae)[0].ToString();
                                excelTable = ExcelDataSource(strFilepathNmae, strExcel).Tables[0];
                                #endregion
                                //data是excel的数据
                                DataTable data = ExcelDataSource(strFilepathNmae, strExcel).Tables[0];
//try
                                    //{
                                if (data != null)
                                {

foreach (DataRow row in data.Rows)
                                        {
                                            //读取
                                        }

}
                                //}
                                //catch (Exception)
                                //{
                                //    Page.ClientScript.RegisterStartupScript(Page.ClientScript.GetType(), "myscript", "<script  type='text/javascript'>$.ligerDialog.closeWaitting();alert('Excel表列名与系统不符合,请检查Excel表列名!');</script>");
                                //    return;
                                //}
                            }
                            else
                            {
                                Page.ClientScript.RegisterStartupScript(Page.ClientScript.GetType(), "myscript", "<script  type='text/javascript'>$.ligerDialog.closeWaitting();alert('您选择的文件不是Excel格式!');</script>");
                                return;
                            }
                        }
                    }
                    finally //最终要把临时存储的文件删除
                    {
                        string strFileFolder = Server.MapPath("~/_layouts/15/images/" + folderTemp + "Upfile/");
                        if (Directory.Exists(strFileFolder)) //根目录
                        {
                            //Directory.CreateDirectory(strFileFolder);//判断上传目录是否存在     自动创建
                            Directory.Delete(strFileFolder, true);
                        }
                        else
                        {
                            Page.ClientScript.RegisterStartupScript(Page.ClientScript.GetType(), "myscript", "<script  type='text/javascript'>ReturnPageValue();</script>");
                        }
                    }
                }
                else
                {
                    Page.ClientScript.RegisterStartupScript(Page.ClientScript.GetType(), "myscript", "<script  type='text/javascript'>$.ligerDialog.closeWaitting();alert('请选择导入文件!');</script>");
                    return;
                }
            });
        }
        protected void BtnClose_Click(object sender, EventArgs e)
        {
            Page.ClientScript.RegisterStartupScript(Page.ClientScript.GetType(), "myscript", "<script  type='text/javascript'>ReturnPageValue();</script>");
        }
        /// <summary>
        /// 连接到Excel
        /// </summary>
        /// <param name="filepath">文件路径</param>
        /// <param name="sheetname">sheet名字</param>
        /// <returns></returns>
        public DataSet ExcelDataSource(string filepath, string sheetname)
        {
            _strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath +
                       ";Extended Properties='Excel 12.0;HDR=YES'";
            new OleDbConnection(_strConn);
            var oada = new OleDbDataAdapter("select * from [" + sheetname + "]", _strConn);
            var ds = new DataSet();
            oada.Fill(ds);
            return ds;
        }
        /// <summary>
        /// 获得Excel中的所有sheetname
        /// </summary>
        /// <param name="filepath">文件路径</param>
        /// <returns></returns>
        public ArrayList ExcelSheetName(string filepath)
        {
            _strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath +
                       ";Extended Properties='Excel 12.0;HDR=YES'";
            var al = new ArrayList();
            var conn = new OleDbConnection(_strConn);
            conn.Open();
            DataTable sheetNames = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
                new object[] { null, null, null, "TABLE" });
            conn.Close();
            if (sheetNames != null)
                foreach (DataRow dr in sheetNames.Rows)
                {
                    al.Add(dr[2]);
                }
            return al;
        }
    }
}

(0)

相关推荐

  • asp.net 读取Excel数据到DataTable的代码

    复制代码 代码如下: /// <summary> /// 获取指定路径.指定工作簿名称的Excel数据:取第一个sheet的数据 /// </summary> /// <param name="FilePath">文件存储路径</param> /// <param name="WorkSheetName">工作簿名称</param> /// <returns>如果争取找到了数据会返回

  • .Net读取Excel 返回DataTable实例代码

    复制代码 代码如下: using System;using Microsoft.SharePoint;using Microsoft.SharePoint.WebControls;using System.Data;using System.IO;using System.Linq;using System.Web;using System.Collections;using System.Data.OleDb;using NuctechProject.DTO.Bll;using System.

  • 利用Python第三方库xlrd读取Excel中数据实例代码

    目录 1. 安装 xlrd 库 2. 使用 xlrd 库 2.1 打开 Excel 工作表对象 2.2 读取单个单元格数据 2.3 读取多个单元格数据 2.3 读取所有单元格数据 附:行.列操作 3. 总结 1. 安装 xlrd 库 Python 读取 Excel 中的数据主要用到 xlrd 第三方库.xlrd 其实就是两个单词的简化拼接,我们可以把它拆开来看,xl 代表 excel, rd 代表 read, 合并起来就是 xlrd, 意思就是读 excel 的第三方库. 这种命名风格也正是我们

  • python读写Excel表格的实例代码(简单实用)

    安装两个库:pip install xlrd.pip install xlwt 1.python读excel--xlrd 2.python写excel--xlwt 1.读excel数据,包括日期等数据 #coding=utf-8 import xlrd import datetime from datetime import date def read_excel(): #打开文件 wb = xlrd.open_workbook(r'test.xlsx') #获取所有sheet的名字 print

  • python使用xlrd和xlwt读写Excel文件的实例代码

    安装模块 如果使用的是Linux系统,并且安装了pip,可以直接使用pip安装xlrd, xlwt: pip install xlwt pip install xlrd 也可以从官网下载源代码安装: https://pypi.org/project/xlwt/1.1.2/ https://pypi.org/project/xlrd/ 下载tar.gz文件,解压,并转到解压后的目录中,找到setup.py,输入命令: sudo python setup.py install 安装完成. 导入模块:

  • SpringBoot读取excel表格的示例代码

    SpringBoot读取excel表格 共同探讨,向各位大佬学习 走向CEO,迎娶白富美 pom.xml依赖 <!--springboot核心依赖--> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.4.RELEASE</vers

  • JS返回顶部实例代码

    本文实例为大家分享了JS返回顶部实例代码,供大家参考,具体内容如下 html/css部分 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="返回顶部效果.js"></script> <style&g

  • 使用Python操作excel文件的实例代码

    使用的类库 pip install openpyxl 操作实现 •工作簿操作 # coding: utf-8 from openpyxl import Workbook # 创建一个excel工作簿 wb = Workbook() # 打开一个工作簿 wb = load_workbook('test.xlsx') # 保存工作簿到文件 wb.save('save.xlsx') •工作表操作 # 获得当前的工作表对象 ws = wb.active # 通过工作表名称得到工作表对象 ws = wb.

  • 可以读取EXCEL文件的js代码第1/2页

    首页给个有中文说明的例子,下面的例子很多大家可以多测试. 复制代码 代码如下: <script language="javascript" type="text/javascript"><!-- function readExcel() { var excelApp; var excelWorkBook; var excelSheet; try{ excelApp = new ActiveXObject("Excel.Applicatio

  • C++中实现把表的数据导出到EXCEL并打印实例代码

    实现把表的数据导出到EXCEL并打印实例代码 首先加入这两句: #include "utilcls.h" #include "comobj.hpp" 下面正式开始: void __fastcall TMainForm::ToExcel(TADOQuery *TT,AnsiString str) {//TT为被导出数据的表,str为命令(具体看代码底部的if语句) #define PG OlePropertyGet #define PS OlePropertySet

  • 基于jQuery实现返回顶部实例代码

    效果图展示如下所示: 使用方法: 只需引用jQuery库和YesTop插件,然后一句代码就可以实现返回顶部: 引用代码: <script type="text/javascript" src="http://hovertree.com/ziyuan/jquery/jquery-1.11.3.min.js"></script> <script type="text/javascript" src="http:

随机推荐