日期:2014-05-19  浏览次数:20834 次

求从SQLserver2000中将表的数据导入到Excel的(C#)的操作代码 用于网页的模式(B/S)
求从SQLserver2000中将表的数据导入到Excel的(C#)的操作代码   用于网页的模式(B/S)

------解决方案--------------------
给你一个从excel到数据库的,反之亦然

public DataSet ExcelToDS(string Path)
{
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0; " + "Data Source= "+ Path + "; "+ "Extended Properties=Excel 8.0; ";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
string strExcel = " ";
OleDbDataAdapter myCommand = null;
DataSet ds = null;
strExcel= "select * from [sheet1$] ";
myCommand = new OleDbDataAdapter(strExcel, strConn);
ds = new DataSet();
myCommand.Fill(ds, "table1 ");
return ds;
}
对于EXCEL中的表即sheet([sheet1$])如果不是固定的可以使用下面的方法得到
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0; " + "Data Source= "+ Path + "; "+ "Extended Properties=Excel 8.0; ";
OleDbConnection conn = new OleDbConnection(strConn);
DataTable schemaTable = objConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables,null);
string tableName=schemaTable.Rows[0][2].ToString().Trim();
Excel文件的写入
public void DSToExcel(string Path,DataSet oldds)
{
//先得到汇总EXCEL的DataSet 主要目的是获得EXCEL在DataSet中的结构
string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = "+path1+ ";Extended Properties=Excel 8.0 " ;
OleDbConnection myConn = new OleDbConnection(strCon) ;
string strCom= "select * from [Sheet1$] ";
myConn.Open ( ) ;
OleDbDataAdapter myCommand = new OleDbDataAdapter ( strCom, myConn ) ;
ystem.Data.OleDb.OleDbCommandBuilder builder=new OleDbCommandBuilder(myCommand);
//QuotePrefix和QuoteSuffix主要是对builder生成InsertComment命令时使用。
builder.QuotePrefix= "[ "; //获取insert语句中保留字符(起始位置)
builder.QuoteSuffix= "] "; //获取insert语句中保留字符(结束位置)
DataSet newds=new DataSet();
myCommand.Fill(newds , "Table1 ") ;
for(int i=0;i <oldds.Tables[0].Rows.Count;i++)
{
//在这里不能使用ImportRow方法将一行导入到news中,因为ImportRow将保留原来DataRow的所有设置(DataRowState状态不变)。在使用ImportRow后newds内有值,但不能更新到Excel中因为所有导入行的DataRowState!=Added
DataRow nrow=aDataSet.Tables[ "Table1 "].NewRow();
for(int j=0;j <newds.Tables[0].Columns.Count;j++)
{
nrow[j]=oldds.Tables[0].Rows[i][j];
}
newds.Tables[ "Table1 "].Rows.Add(nrow);
}
myCommand.Update(newds, "Table1 ");
myConn.Close();
}

------解决方案--------------------
将sql server中的数据倒入Excel

author:ouyang76cn()

虽然,sql server中的DTS也能将数据倒入Excel,但不如使用程序灵活,

本程序主要代码在按钮函数内。可适应于报表开发的读取数据部分:)

我删除了原程序的很多垃圾代码,只留主要起作用的代码

//加入名称空间

using System.Data;

using System.Data.SqlClient;

//定义方法GetData(),返回一个数据表

private System.Data.DataTable GetData()

{

SqlConnection conn= new SqlConnection(@ "Server=PXGD2;Initial Catalog=pingxiang;Uid=sa;Pwd=; ");

SqlDataAdapter adapter= new SqlDataAdapter( "select username 用户名,catalyst_port 占用端口,home_address 住宅地址,ip_address

ip地址,phone 电话,addtime 开通日期 from userinfo where catalyst_port=1 or catalyst_port= ' order by ip_address desc ",conn);

DataSet ds= new DataSet();

try

{

adapter.Fill(ds, "Customer ");

}

catch(Exception ex)

{

MessageBox.Show(ex.ToString());

}

return ds.Tables[0];

}

//按钮