• 大小: 36KB
    文件类型: .cs
    金币: 1
    下载: 0 次
    发布日期: 2021-05-04
  • 语言: C#
  • 标签: C#  Excel  

资源简介

通用类,专门用来操作Excel .包含 读取 导出 写入 等功能

资源截图

代码片段和文件信息

//C#读取Excel
 
private void ReadExcel(){
 
        OleDbCommand cmd = null;
            OleDbConnection conn = null;
            string fileName = hidFileName.Text + “.xls“;
            string filePath = Path.Combine(Server.MapPath(“Excell/ImportExcelTempFolder“) fileName);
            try
            {
                String connString = “Provider=Microsoft.Jet.OLEDB.4.0;“ +
                  “Data Source=“ + filePath + “;Extended Properties=\“Excel 8.0;HDR=YES;IMEX=1\““;
 
                string message = ““;
                int count = 0;
                using (conn = new OleDbConnection(connString))
                {
                    if (conn.State == ConnectionState.Closed)
                        conn.Open();
                    cmd = conn.CreateCommand();
                    string strSql = “SELECT [老师] [课程][年级][班级][合作老师]  FROM [授课安排$]“;
                    cmd.CommandText = strSql;
                    using (OleDbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                    {
                        int i = 0;
                        while (dr.Read())
                        {
                            i++;
 
                            ......
 
                         }
 
         }
 
      }
 
           }
 
     catch (Exception ex)
            {
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
                throw ex;
            }
            finally
            {
                if (conn != null && conn.State == ConnectionState.Open)
                    conn.Close();
            }
 
}
 
//C#导出为Excel
 
//这里我写了一个通用类,专门用来操作Excel 
 
 
 
using System;
using System.IO;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Globalization;
using System.Collections;
using System.Data.OleDb;
 
namespace Com.DRPENG.SDXY.UI.Common
{
    public class ExcelHelper
    {
        static object obj = new object();
        #region Fields
        string _fileName;
        DataTable _dataSource;
        string[] _titles = null;
        string[] _fields = null;
        int _maxRecords = 1000;
 
        #endregion
 
        #region Properties
 
        ///  
        /// 限制输出到 Excel 的最大记录数。超出则抛出异常 
        /// 
 
        public int MaxRecords
        {
            set { _maxRecords = value; }
            get { return _maxRecords; }
        }
 
        ///  
        /// 输出到浏览器的 Excel 文件名 
        /// 
 
        public string FileName
        {
            set { _fileName = value; }
            get { return _fileName; }
        }
 
        #endregion
 
        #region .ctor
 
        ///  
        /// 构造函数 
        /// 
 
        /// tles“>要输出到 Excel 的列标题的数组 
        /// 要输出到

评论

共有 条评论