Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Dec 4, 2008

C# 操作 Excel

// 连接字符串
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;";
strConn += "Extended Properties='Excel 8.0;HDR=No; IMEX=1;';";
strConn += "data source=" + xlsPath;

// 查询语句
string cmdText = "SELECT * FROM [Sheet1$]";

OleDbConnection connDB = new OleDbConnection(strConn);
OleDbCommand cmdDB = new OleDbCommand(cmdText, connDB);
OleDbDataReader drdr;

// 打开Excel表格
connDB.Open();

// 执行 sql语句
drdr = cmdDB.ExecuteReader();


if(drdr.Read())
{
..............

drdr.GetValue(i)

...............

}

C# 从Web网站下载文件

// 给出文件的url和文件下载后的文件绝对路径
// 从服务器下载文件
// 成功返回 true,否则返回false
// using System.Net;

private bool DownloadFile(string url, string strfile)
{
HttpWebRequest hwr = null;
Stream ns = null;

FileStream fs = new FileStream(strfile, FileMode.Create);
int nReadSize = 0;
byte[] abytes = new byte[1025];

try
{
hwr = (HttpWebRequest)WebRequest.Create(url);
ns = hwr.GetResponse().GetResponseStream();
nReadSize = ns.Read(abytes, 0, 1024);
while (nReadSize > 0)
{
fs.Write(abytes, 0, nReadSize);
nReadSize = ns.Read(abytes, 0, 1024);
}
fs.Close();
ns.Close();
}
catch (Exception eer)
{
MessageBox.Show(eer.Message);
fs.Close();
File.Delete(strfile);
return false;
}

return true;
}

Oct 21, 2008

C# 读取gb2312文本文件

StreamReader objReader = new StreamReader(strFilename,System.Text.Encoding.GetEncoding("gb2312"));

如果不加第二个参数,读出来的中文是乱码