C# 获得.xls文件的内容 获得.xls文件中的表名 – 曾经的曾经 – 博客园
http://www.cnblogs.com/pro_net/archive/2009/02/27/1400049.html
private void ExcelToDS(string Path)
{
string clientFilePath = FileUpload1.PostedFile.FileName; //客户端文件的物理路径
int i = clientFilePath.LastIndexOf(“.”); //取得文件名中最后一个”.”的索引
string extension = clientFilePath.Substring(i); //获取文件扩展名
if (extension != “.xls”)
{
MsgBox.Alert(“文件必须为.xls格式!”, “ImportTeacherDate.aspx”);
return;
}
else
{
string myConn = “Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = ‘” + clientFilePath + “‘;Extended Properties=Excel 8.0″;
OleDbConnection cnnxls = new OleDbConnection(myConn);
DataSet myDataSet = new DataSet(); //创建DataSet对象
cnnxls.Open();
DataTable dt = cnnxls.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string StyleSheet = dt.Rows[0][2].ToString().Trim(); //.xls的第一个表名
string StrSql = string.Format(“SELECT * FROM [{0}]“, StyleSheet);
OleDbDataAdapter myCommand = new OleDbDataAdapter(StrSql, myConn);
myCommand.Fill(myDataSet, string.Format(“[{0}]“, StyleSheet));
myCommand.Dispose();
DataTable DT = myDataSet.Tables[string.Format("[{0}]“, StyleSheet)];
for (int j = 0; j < DT.Rows.Count; j++)
{
try
{
string userLogin = BusinessFacadeFrameWork.get_table_fileds(“FrameWork_Member”, “Name”, “Name”, DT.Rows[j][0].ToString().Trim());
if (!string.IsNullOrEmpty(userLogin))
{
MsgBox.Alert(string.Format(“添加教师失败!{0}的登录名已存在!”, DT.Rows[j][0].ToString()), “ImportTeacherDate.aspx”);
return;
}
else
{
//向用户表内添加老师基本信息
FrameWork_MemberEntity me = new FrameWork_MemberEntity();
me.DataTable_Action_ = DataTable_Action.Insert;
me.Name = DT.Rows[j][0].ToString().Trim();
me.PSW = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(“123456″, “MD5″).ToUpper();
me.RegTime = DateTime.Now;
me.TrueName = DT.Rows[j][1].ToString().Trim();
me.MemberRoleID = 6;
int rInt = BusinessFacadeFrameWork.FrameWork_MemberInsertUpdateDelete(me);
if (rInt < 1)
{
MsgBox.Alert(“向用户表内添加老师基本信息失败!”, “ImportTeacherDate.aspx”);
return;
}
else
{
//向教师表内添加教师详细信息
FrameWork_TeacherEntity te = new FrameWork_TeacherEntity();
te.DataTable_Action_ = DataTable_Action.Insert;
te.cLogin = DT.Rows[j][0].ToString().Trim();
te.cName = DT.Rows[j][1].ToString().Trim();
te.cIntro = DT.Rows[j][2].ToString().Trim();
te.cPos = DT.Rows[j][3].ToString().Trim();
te.cPhoto = DT.Rows[j][4].ToString().Trim();
te.cTeacherCode = AdminLoginInfo.CCode;
te.cTeachTel = DT.Rows[j][5].ToString().Trim();
int rInt_te = BusinessFacadeFrameWork.FrameWork_TeacherInsertUpdateDelete(te);
if (rInt_te < 1)
{
MsgBox.Alert(“向用户表内添加老师基本信息失败!”, “ImportTeacherDate.aspx”);
return;
}
}
}
}
catch (Exception ex)
{
MsgBox.Alert(“用户提供的表格格式不正确”, “ImportTeacherDate.aspx”);
return;
}
}
cnnxls.Close();
MsgBox.Alert(“导入教师数据成功!”, “TeacherList.aspx?ModelID=500″);
}
}
将DBF,XLS,XML,MDB文件导入C#DataGrid的方法,个人站长站教程
http://www.chinageren.com/chengxu/ASP_NET/chengxu_30079.html
//PutInDataSet.cs的源码
using System;
using System.Data.Odbc;
using System.Data.OleDb;
using System.Data;
using System.Collections;
namespace PutInDataSet
{
/// <summary>
/// DataSetTransIn 的摘要说明。
/// </summary>
public class PutInDataSet
{
/// <summary>
/// 传入的文件变量
/// </summary>
private DataSet my_Ds;//存放文件的数据集
private string my_Err;//错误信息
private string my_TableName;//传入的文件名
private TableType my_TableType;//传入的文件类型
private string my_TablePath;//传入的文件路径
private int my_TableIndex;//表的索引
OleDbCommandBuilder my_Builder;//命令串
/// <summary>
/// 数据库连接变量
/// </summary>
private string my_StrConnection;//连接字符串
private string my_StrSelect;//select语句
/// <summary>
/// 可以处理的文件类型
/// </summary>
public enum TableType
{
MDB,XLS,DBF,DOC,TXT,XML,HTML
}
public PutInDataSet(string TablePath,string TableName,TableType TableType)
{
///<summary>
///获得传入的路径,文件名及文件类型;
///</summary>
this.my_TablePath=TablePath;//路径
this.my_TableName=TableName;//文件名
this.my_TableType=TableType;//文件类型
}
public DataSet Convert()
{
DataSet iRtn_Ds=new DataSet();
switch (this.my_TableType)
{
case TableType.DBF:
iRtn_Ds = this.DbfToDs();
break;
case TableType.MDB:
iRtn_Ds = this.MdbToDs();
break;
case TableType.XLS:
iRtn_Ds = this.XlsToDs();
break;
case TableType.XML:
iRtn_Ds = this.XmlToDs();
break;
}
return iRtn_Ds;
}
///<summary>
///将DBF文件放入DataSet
///</summary>
private DataSet DbfToDs()
{
//数据库连接定义
OdbcConnection my_conn; //数据连接
OdbcDataAdapter my_Adapter;//数据适配器
//数据库连接
this.my_StrConnection= “Driver={Microsoft Visual FoxPro Driver};SourceType=DBF;SourceDB=” + this.my_TablePath;
this.my_StrSelect=”SELECT * FROM ” + this.my_TableName;
my_conn = new OdbcConnection(this.my_StrConnection);
my_conn.Open();
my_Adapter = new OdbcDataAdapter(this.my_StrSelect,my_conn);
this.my_Ds=new DataSet();
//填充数据集
my_Adapter.Fill(this.my_Ds,this.my_TableName);
return this.my_Ds;
}
///<summary>
///将MDB文件放入DataSet
///</summary>
private DataSet MdbToDs()
{
//数据库连接定义
OleDbConnection my_conn;
OleDbDataAdapter my_Adapter;
//数据库连接
this.my_StrConnection= “Provider=Microsoft.JET.OLEDB.4.0;data source=” + this.my_TablePath;
this.my_StrSelect=”SELECT * FROM ” + this.my_TableName;
my_conn = new OleDbConnection(this.my_StrConnection);
my_conn.Open();
my_Adapter = new OleDbDataAdapter(this.my_StrSelect,my_conn);
this.my_Ds=new DataSet();
//填充数据集
my_Adapter.Fill(this.my_Ds,this.my_TableName);
return this.my_Ds;
}
///<summary>
///将XML文件放入DataSet
///</summary>
private DataSet XmlToDs()
{
//填充数据集
this.my_Ds=new DataSet();
this.my_Ds.ReadXml(this.my_TablePath+this.my_TableName,XmlReadMode.ReadSchema);
this.my_Ds.DataSetName=”XmlData”;
return this.my_Ds;
}
///<summary>
///将Excel文件放入DataSet
///</summary>
private DataSet XlsToDs()
{
OleDbConnection my_conn;
OleDbDataAdapter my_Adapter;
//数据库连接
this.my_StrConnection= “Provider=Microsoft.JET.OLEDB.4.0;Extended Properties=Excel 8.0;data source=”+this.my_TablePath+this.my_TableName;
this.my_StrSelect=”SELECT * FROM [SHEET1$]“;
my_conn = new OleDbConnection(this.my_StrConnection);
my_conn.Open();
my_Adapter = new OleDbDataAdapter(this.my_StrSelect,my_conn);
this.my_Builder=new OleDbCommandBuilder(my_Adapter);
this.my_Ds=new DataSet();
//填充数据集
my_Adapter.Fill(this.my_Ds,”ExcelData”);
return this.my_Ds;
}
}
}
//Form_PutInDataSet.cs的源码
using System;
using System.Data;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using DataAccess.SysManage;
using BusinessRules;
using DataSetTrans;
namespace WinForm.Common
{
/// <summary>
/// FormDesktop 的摘要说明。
/// </summary>
public class FormDesktop : System.Windows.Forms.Form
{
private WinForm.Common.DeskTop deskTop1;
private System.Windows.Forms.Button button1;
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;
private DataSet m_ds = new DataSet();
private System.Windows.Forms.DataGrid dataGrid1; //数据源
private string m_TableName; //外部文件名称
public FormDesktop()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();
//
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
}
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// 设计器支持所需的方法 – 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.deskTop1 = new WinForm.Common.DeskTop();
this.button1 = new System.Windows.Forms.Button();
this.dataGrid1 = new System.Windows.Forms.DataGrid();
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
this.SuspendLayout();
//
// deskTop1
//
this.deskTop1.BackColor = System.Drawing.SystemColors.Desktop;
this.deskTop1.Location = new System.Drawing.Point(168, 440);
this.deskTop1.Name = “deskTop1″;
this.deskTop1.Size = new System.Drawing.Size(16, 24);
this.deskTop1.TabIndex = 0;
//
// button1
//
this.button1.Location = new System.Drawing.Point(256, 216);
this.button1.Name = “button1″;
this.button1.Size = new System.Drawing.Size(88, 40);
this.button1.TabIndex = 1;
this.button1.Text = “GetData”;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// dataGrid1
//
this.dataGrid1.DataMember = “”;
this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dataGrid1.Location = new System.Drawing.Point(192, 40);
this.dataGrid1.Name = “dataGrid1″;
this.dataGrid1.Size = new System.Drawing.Size(216, 152);
this.dataGrid1.TabIndex = 2;
//
// FormDesktop
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.BackColor = System.Drawing.SystemColors.AppWorkspace;
this.ClientSize = new System.Drawing.Size(624, 485);
this.Controls.Add(this.dataGrid1);
this.Controls.Add(this.button1);
this.Controls.Add(this.deskTop1);
this.Name = “FormDesktop”;
this.Text = “系统控制台”;
this.Resize += new System.EventHandler(this.FormDesktop_Resize);
this.Load += new System.EventHandler(this.FormDesktop_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private void FormDesktop_Load(object sender, System.EventArgs e)
{
}
/// <summary>
/// 当窗口改变大小时自动居中。
/// </summary>
private void FormDesktop_Resize(object sender, System.EventArgs e)
{
if (this.WindowState != FormWindowState.Minimized)
{
if (this.Width > this.deskTop1.Width && this.Height > this.deskTop1.Height )
{
this.deskTop1.Left = (this.Width – this.deskTop1.Width) / 2;
this.deskTop1.Top = (this.Height- this.deskTop1.Height)/ 2;
}
}
}
private void button1_Click(object sender, System.EventArgs e)
{
DataSet out_Ds=new DataSet();
PutInDataSet obj=new PutInDataSet(“文件路径”,”文件名”,PutInDataSet.TableType.文件格式);//调用PutInDataSet类
out_Ds=obj.Convert();//转换到DataSet中
this.dataGrid1.DataSource=out_Ds.Tables["表名"];//在DataGrid中显示
}
}
}
历史博文
- 20080326 ExtJs try catch - 2008
- 20070722 WEB WEBService 同步 异步 - 2007
- 0710 buildx GForge - 2006
- 1218 apache php 配置 - 2005