文档目录
1. 获取本机ip地址
2. 获取客户端IP地址
3. 获取网卡IP地址
4. CSharp获取上一页URL
5. 获取网站域名
6. ServerVariables变量列表
7. 在HTML页面中引入命名空间
8. 日期(年、月、日、星期)显示
9. DateTime类型赋空值
10. 判断dataset是否为空
11. 记事本编码设置
12. 将指定的虚拟路径转向物理路径
13. 读取目录下所有文件夹
14. 读取txt文件
15. 上传文件到数据库,然后下载文件
16. 图片上加文字
17. CSharp读取Word文档
18. DataTable导入导出Excel
19. DataTable排序
20. 截取字符串长度
21. 邮件发送
22. 绑定多组数据
23. Eval绑定数据
24. 除法运算
25. 将数字转化为字母(A~Z)
26. ASCⅡ码对照表
27. 字符串与字节数组转换
28. 由于代码已经过优化或者本机框架位于调用堆栈之上……
获取本机ip地址
c#怎么获取本机ip地址?----1
System.Net.IPAddress[] addressList =Dns.GetHostByName(Dns.GetHostName()).AddressList;
textBox1.Text =addressList[0].ToString ();
c#怎么获取本机ip地址?----2
MachineName = System.Net.Dns.GetHostName();
System.Net.IPAddress addr;
// 获得本机局域网IP地址
addr = new System.Net.IPAddress(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].Address);
IpAddress = addr.ToString();
获取服务器的IP地址方法以DNS法较为简单实用,如下:
using System.Net;
private void ButtonIP_Click(object sender, System.EventArgs e)
{
System.Net.IPAddress[] addressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;
if ( addressList.Length>1)
{ TextLIP.Text = addressList[0].ToString();
TextSIP.Text = addressList[1].ToString();
}
else
{
TextLIP.Text = addressList[0].ToString();
TextSIP.Text = "没有可用的连接";
}
}
C#获取客户端IP地址?
string ip="";
if(this.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]!=null && this.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].Trim()!="")
{
ip=this.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
ip=ip.ToLower().Replace("unknown","").Trim();
Response.Write("
HTTP_X_FORWARDED_FOR:" + ip);
}
if(this.Request.ServerVariables["REMOTE_ADDR"]!=null && this.Request.ServerVariables["REMOTE_ADDR"].Trim()!="")
{
if ( ip=="" || ip==null)
ip=this.Request.ServerVariables["REMOTE_ADDR"];
ip=ip.ToLower().Replace("unknown","").Trim();
Response.Write("
REMOTE_ADDR(代理服务器IP地址):" + this.Request.ServerVariables["REMOTE_ADDR"]);
}
if(this.Request.ServerVariables["REMOTE_HOST"]!=null && this.Request.ServerVariables["REMOTE_HOST"].Trim()!="")
{
if ( ip=="" || ip==null)
ip=this.Request.ServerVariables["REMOTE_HOST"];
ip=ip.ToLower().Replace("unknown","").Trim();
Response.Write("
REMOTE_HOST:" + this.Request.ServerVariables["REMOTE_HOST"]);
}
/*
//穿过代理服务器取远程用户真实IP地址:
if(this.Request.ServerVariables["HTTP_VIA"]!=null)
{
ip=this.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
else
{
ip=this.Request.ServerVariables["REMOTE_ADDR"].ToString();
}
*/
if(ip=="" || ip==null)
ip="127.0.0.1";
Response.Write("
ip:" +ip);
-- ServerVariables变量列表
|
C# 获取网卡IP地址
using System.Net.NetworkInformation; NetworkInterface[] NetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces(); |
C# 获取上一页URL
Request.UrlReferrer.ToString()
C# 获取网站域名
1Request.Url.GetLeftPart(UriPartial.Authority)
2Request.ServerVariables["server_name"]
C#中如何在HTML页面中引入命名空间?
<%@Import Namespace="System.Data"%>
日期显示
(1)
public string TodayTime; //声明共有变量,页面调用
protected void Page_Load(object sender, EventArgs e)
{
TodayTime=serverTimes();
}
private string serverTimes()
{
string strENU = DateTime.Now.DayOfWeek.ToString();
string strCHS = "";
string strServerTime = "";
if (strENU == "Sunday") strCHS = "星期日";
else if (strENU == "Monday") strCHS = "星期一";
else if (strENU == "Tuesday") strCHS = "星期二";
else if (strENU == "Wednesday") strCHS = "星期三";
else if (strENU == "Thursday") strCHS = "星期四";
else if (strENU == "Friday") strCHS = "星期五";
else strCHS = "星期六";
strServerTime = "今天是"+DateTime.Now.Year.ToString() + "年" + DateTime.Now.Month.ToString() + "月" + DateTime.Now.Day.ToString() + "日 " + strCHS;
return strServerTime;
}
(2)public string ShowTime()
{
string weekey,DateStr;
weekey="";
switch((int)DateTime.Now.DayOfWeek){
case 0:{ weekey="星期日";break;}
case 1:{ weekey="星期一";break;}
case 2:{ weekey="星期二";break;}
case 3:{ weekey="星期三";break;}
case 4:{ weekey="星期四";break;}
case 5:{ weekey="星期五";break;}
case 6:{ weekey="星期六";break;}
}
DateStr=DateTime.Now.Year+"年"+DateTime.Now.Month+"月"+DateTime.Now.Day+"日 "+weekey;
return DateStr;
}
DataBinder Eval 前台绑定 经验总结
一、DataBinder.Eval的基本格式
在绑定数据时经常会用到这个句程序:
<%# DataBinder.Eval(Container.DataItem,"xxxx")%>
或者
<%# DataBinder.Eval(Container,"DataItem.xxxx")%>
或者
<%# ((DataRowView)Container.DataItem)["xxxx"]%>
或者
<%# ((DictionaryEntry)Container.DataItem).Key%>
在后台:
Text='<%# DataBinder.Eval(Container.DataItem, "字段") %>' 这样的方法是最快的
Text='<%# GetPrice() %>' 也可以绑定方法,但方法要是public的
Text='<%# "CarDetails.aspx?CarID=" + DataBinder.Eval(Container.DataItem, "CarID") %>'
还可以连接多个字段
二、DataBinder.Eval实现判断选择
<%# DGFormatSex(Convert.ToString(DataBinder.Eval(Container.DataItem,"xb"))) %>
cs里定义DGFormatSex方法
protected string DGFormatSex(string xb)
{
if(xb == "1")
return "男";
else
return "女";
}
三、Eval的Format参数:
1、显示二位小数:
<%# DataBinder.Eval(Container.DataItem, "UnitPrice", "${0:F2}") %>
2、{0:G}代表显示True或False:
ImageUrl='<%# DataBinder.Eval(Container.DataItem, "Discontinued", "~/p_w_picpaths/{0:G}.gif") %>' />
3、转换类型
((string)DataBinder.Eval(Container, "DataItem.P_SHIP_TIME_SBM8")).Substring(4,4)
4、简要说明:
{0:d} 日期只显示年月日
{0:yyyy-mm-dd} 按格式显示年月日
{0:c} 货币样式
C#除法运算
decimal All, o1v, o2v,bl, d1, d2;
All = vot.Option1Value + vot.Option2Value;
o1v = vot.Option1Value;
o2v = vot.Option2Value;
d1 = 10000.0m ;
d2 = 100.0m ;
bl = Math.Round(o1v / All * d1 / d2, 2);
response.write(bl);
(投票)票数图片显示
int ImgBarWidth = 320;
decimal v4 = bl * ImgBarWidth / 100;
+ v4 + " align=absMiddle>
数据绑定控件 绑定多组数据
DocumentService.DocumentService serv = new Xiaoyaosr.Channel.Web.DocumentService.DocumentService();
string[] _ids = _chnId.Split(',');
ArrayList al = new ArrayList();
int splitCount = _count/_ids.Length;
int tmpCount=0;
for (int i = 0; i < _ids.Length; i++)
{
tmpCount += splitCount;
if (i == _ids.Length - 1 && tmpCount < _count)
splitCount++;
Xiaoyaosr.Channel.Web.DocumentService.XiaoyaosrDocument[] docs =serv.getFixedDocsByChnId(Convert.ToInt32(_ids[i]), splitCount);
al.AddRange(docs);
}
dl_left.DataSource = al;
dl_left.DataBind();
字符串处理
|截取字符串长度|
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
namespace Xiaoyaosr.Common
{
public class Format
{
///
/// 截断字符串长度
///
///
///
///
///
public static String Trunc(Object obj, int len, String suffix)
{
if (obj == null) return null;
return Trunc(obj.ToString(), len, suffix);
}
///
/// 截断字符串长度
///
/// 要截断的字符串
/// 长度
///
///
public static String Trunc(String str, int len, String suffix)
{
if (suffix == null) suffix = "";
str = HttpUtility.HtmlDecode(str.Trim());
int max = str.Length;
if (max <= len)
return str;
int i = len;
len *= 2;
//创建GBK码对象
System.Text.Encoding gbk = System.Text.Encoding.GetEncoding(936);
while (i < max)
{
String prefix = str.Substring(0, i);
byte[] des = gbk.GetBytes(prefix);
int encoded = des.Length;
if (encoded == len)
return prefix + suffix;
else if (encoded > len)
return str.Substring(0, i - 1) + suffix;
i++;
}
if (gbk.GetBytes(str).Length > len)
return str.Substring(0, max - 1) + suffix;
else
return str;
}
}
}
----------DateTime类型赋空值-------------
DateTime类型的值是不能为空值(null)的,如果想让时间类型的变量有空值,可以用如下的声明形式:
DateTime? time=null;
或者设置DateTime的初始值为最小值:DateTime.MinValue();
-------------页面循环绑定-------------------
<% DataTable myTable = Xiaoyaosr.Document.Web.Component.SystemUtility.GetCatalogs();
foreach (DataRow row in myTable.Rows)
{
%>
onmouseout="leftBgOut(this,'../Images/left_bg01.gif');"> <%=row["ChnName"].ToString()%>
<%} %>
-------------邮件发送-----------------
public void SendMail(string From,string To,string Subject,string Body)
{
System.Web.Mail.SmtpMail.SmtpServer="mail.Xiaoyaosr.com.cn";
try
{
System.Web.Mail.MailMessage m1=new System.Web.Mail.MailMessage();
m1.From=From;
m1.To=To;
m1.Subject=Subject;
m1.Body=Body;
m1.BodyFormat=System.Web.Mail.MailFormat.Html;
m1.Priority=System.Web.Mail.MailPriority.High;
System.Web.Mail.SmtpMail.Send(m1);
}
catch
{}
}
DateTime类型赋空值
DateTime类型的值是不能为空值(null)的,如果想让时间类型的变量有空值,可以用如下的声明形式:
DateTime? ? time=null;
判断dataset是否为空
应该先判断是否数据集为空(查询出错时),接着判断表中的行数是否为零(查询未出错且行数是否为零),否则容易出错,
例如:先判断myDataSet.Tables[0].Rows.Count==0时,如果查询出错时,此时myDataSet为null,也就没有table,所以会报错。
故应该这样判断
if (myDataSet == null || myDataSet.Tables[0].Rows.Count == 0)
{
//为空时进行处理
}
else
{
//不为空时处理
}
“||”和“&&”操作符先判断第一个条件,不满足后接着判断下一条件,但如果上面顺序调换在myDataSet为null时则会出错,即先判断大的条件,接着判断小的条件
将指定的虚拟路径转向物理路径
Request .MapPath(strPath) ;
记事本编码设置为UTF-8,解决乱码。
读取目录flv下所有文件夹
private void ReadFiles()
{
try
{
strFilePath = Request.MapPath("~\\flv");
if (Directory.Exists(strFilePath))
{
Directory.GetDirectories(strFilePath + "/");
}
DirectoryInfo dir = new DirectoryInfo(strFilePath);
DirectoryInfo[] inf = dir.GetDirectories();
string str = " string str2 = ""; ///按最后修改时间倒序排列文件夹 DateTime Temp = DateTime.Now; int n = inf.Length; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (inf[i].LastWriteTime < inf[j].LastWriteTime) { Temp = inf[i].LastWriteTime; inf[i].LastWriteTime = inf[j].LastWriteTime; inf[j].LastWriteTime = Temp; } } } foreach (DirectoryInfo strFolder in inf) { str2 = ReadData(strFolder.ToString()); } str += str2 + "";
";
this.ltlTableList.Text = str;
}
catch (Exception e)
{
lblErrMessage.Text = e.Message;
}
}
读取readme.txt文件
(1) private string ReadData(string strFlvName)
{
strFilePath = Request.MapPath("~\\flv");
string strTxtPath = strFilePath+"\\" + strFlvName +"\\readme.txt";
StreamReader sr = new StreamReader(strTxtPath);
sr.BaseStream.Seek(0, SeekOrigin.Begin);
string str = sr.ReadLine();
string[] array = str.Split("#&".ToCharArray());
if (array.Length > 0)
{
strTitle = array[0].ToString();
strDate = array[2].ToString();
strUploader = array[4].ToString();
strIntroduce = array[6].ToString();
}
sr.Close();
//fs.Close();
strTableList += " strTableList += "上 传 者: " + strUploader + " strTableList += "上传日期: " + strDate + " strTableList += "简 介: " + strIntroduce + " "; " + strTitle + "
";
";
";
return strTableList;
}
(2) 如何使用 System.IO 和 Visual C# 读取文本文件
using System;
using System.IO;
using System.Collections;
namespace TextFileReader_csharp
{
///
/// Summary description for Class1.
///
class Class1
{
static void Main(string[] args)
{
StreamReader objReader = new StreamReader("c:\\test.txt");
string sLine="";
ArrayList arrText = new ArrayList();
while (sLine != null)
{
sLine = objReader.ReadLine();
if (sLine != null)
arrText.Add(sLine);
}
objReader.Close();
foreach (string sOutput in arrText)
Console.WriteLine(sOutput);
Console.ReadLine();
}
}
}
C#读取Word文档
1: 对项目添加引用,Microsoft Word 11.0 Object Library
2: 在程序中添加 using Word = Microsoft.Office.Interop.Word;
3: 程序中添加
Word.Application app = new Microsoft.Office.Interop.Word.Application(); //可以打开word程序
Word.Document doc = null; //一会要记录word打开的文档
word文档和word程序可不是一回事奥!
4: 一般来说,对于抽取word内容,用的方法很少
public override void openFile(object fileName){} //打开文档
public override object readPar(int i){} //读取word文档的第i段
public override int getParCount(){} //返回word文档一共几段
public override void closeFile(){} //关闭文档
public override void quit(){} //关闭word程序
//从网页上拷贝的目录有时候会出现手动换行符^l,,先将其换成回车段落标记,才能正确读取
public void replaceChar(){}
5:代码
public override void openFile(object fileName)
{
try
{
if (app.Documents.Count > 0)
{
if (MessageBox.Show("已经打开了一个word文档,你想关闭重新打开该文档吗?", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
object unknow = Type.Missing;
doc = app.ActiveDocument;
if (MessageBox.Show("你想保存吗?", "保存", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
app.ActiveDocument.Save();
}
app.ActiveDocument.Close(ref unknow, ref unknow, ref unknow);
app.Visible = false;
}
else
{
return;
}
}
}
catch (Exception)
{
//MessageBox.Show("您可能关闭了文档");
app = new Microsoft.Office.Interop.Word.Application();
}
try
{
object unknow = Type.Missing;
app.Visible = true;
doc = app.Documents.Open(ref fileName,
ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);
}
catch (Exception ex)
{
MessageBox.Show("出现错误:" + ex.ToString());
}
}
public override object readPar(int i)
{
try
{
string temp = doc.Paragraphs[i].Range.Text.Trim();
return temp;
}
catch (Exception e) {
MessageBox.Show("Error:"+e.ToString());
return null;
}
}
public override int getParCount()
{
return doc.Paragraphs.Count;
}
public override void closeFile()
{
try
{
object unknow = Type.Missing;
object saveChanges = Word.WdSaveOptions.wdPromptToSaveChanges;
app.ActiveDocument.Close(ref saveChanges, ref unknow, ref unknow);
}
catch (Exception ex)
{
MessageBox.Show("Error:" + ex.ToString());
}
}
public override void quit()
{
try
{
object unknow = Type.Missing;
object saveChanges = Word.WdSaveOptions.wdSaveChanges;
app.Quit(ref saveChanges, ref unknow, ref unknow);
}
catch (Exception)
{
}
}
public void replaceChar() {
try
{
object replaceAll = Word.WdReplace.wdReplaceAll;
object missing = Type.Missing;
app.Selection.Find.ClearFormatting();
app.Selection.Find.Text = "^l";
app.Selection.Find.Replacement.ClearFormatting();
app.Selection.Find.Replacement.Text = "^p";
app.Selection.Find.Execute(
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref replaceAll, ref missing, ref missing, ref missing, ref missing);
}
catch (Exception e)
{
MessageBox.Show("文档出现错误,请重新操作");
}
}
6:
刚才是用读取一段做的例子,如果要读取一句或一篇只需要把doc.Paragraphs[i](readPar中)改成doc.Sentences[i]或doc.content即可,因为都是微软的东东,所以用起来没有一点的障碍,再加上现在的vs2005做的很智能,所以先从java转到了c#上
7:
实际上,c#中读取word是不用那么麻烦的,但是如果考虑到可能还要抽取txt,ppt等多种格式,所以就写了一个抽象类,调用起来也方便,这就是为什么我的程序方法开头会有override的原因,总要考虑到通用,所以多了一些代码。
///
/// A-Z初始化,将数字循环转化为字母(A-Z)
///
private void WordBind()
{
string[] aa = new string[26];
for (int i = 0; i < aa.Length; i++)
{
char a = (char)(i + 65);
string s = a.ToString();
}
}
ASCⅡ码对照表
八进制 |
十六进制 |
十进制 |
字符 |
八进制 |
十六进制 |
十进制 |
字符 |
00 |
00 |
0 |
nul |
100 |
40 |
64 |
@ |
01 |
01 |
1 |
soh |
101 |
41 |
65 |
A |
02 |
02 |
2 |
stx |
102 |
42 |
66 |
B |
03 |
03 |
3 |
etx |
103 |
43 |
67 |
C |
04 |
04 |
4 |
eot |
104 |
44 |
68 |
D |
05 |
05 |
5 |
enq |
105 |
45 |
69 |
E |
06 |
06 |
6 |
ack |
106 |
46 |
70 |
F |
07 |
07 |
7 |
bel |
107 |
47 |
71 |
G |
10 |
08 |
8 |
bs |
110 |
48 |
72 |
H |
11 |
09 |
9 |
ht |
111 |
49 |
73 |
I |
12 |
0a |
10 |
nl |
112 |
4a |
74 |
J |
13 |
0b |
11 |
vt |
113 |
4b |
75 |
K |
14 |
0c |
12 |
ff |
114 |
4c |
76 |
L |
15 |
0d |
13 |
er |
115 |
4d |
77 |
M |
16 |
0e |
14 |
so |
116 |
4e |
78 |
N |
17 |
0f |
15 |
si |
117 |
4f |
79 |
O |
20 |
10 |
16 |
dle |
120 |
50 |
80 |
P |
21 |
11 |
17 |
dc1 |
121 |
51 |
81 |
Q |
22 |
12 |
18 |
dc2 |
122 |
52 |
82 |
R |
23 |
13 |
19 |
dc3 |
123 |
53 |
83 |
S |
24 |
14 |
20 |
dc4 |
124 |
54 |
84 |
T |
25 |
15 |
21 |
nak |
125 |
55 |
85 |
U |
26 |
16 |
22 |
syn |
126 |
56 |
86 |
V |
27 |
17 |
23 |
etb |
127 |
57 |
87 |
W |
30 |
18 |
24 |
can |
130 |
58 |
88 |
X |
31 |
19 |
25 |
em |
131 |
59 |
89 |
Y |
32 |
1a |
26 |
sub |
132 |
5a |
90 |
Z |
33 |
1b |
27 |
esc |
133 |
5b |
91 |
[ |
34 |
1c |
28 |
fs |
134 |
5c |
92 |
\ |
35 |
1d |
29 |
gs |
135 |
5d |
93 |
] |
36 |
1e |
30 |
re |
136 |
5e |
94 |
^ |
37 |
1f |
31 |
us |
137 |
5f |
95 |
_ |
40 |
20 |
32 |
sp |
140 |
60 |
96 |
' |
41 |
21 |
33 |
! |
141 |
61 |
97 |
a |
42 |
22 |
34 |
" |
142 |
62 |
98 |
b |
43 |
23 |
35 |
# |
143 |
63 |
99 |
c |
44 |
24 |
36 |
$ |
144 |
64 |
100 |
d |
45 |
25 |
37 |
% |
145 |
65 |
101 |
e |
46 |
26 |
38 |
& |
146 |
66 |
102 |
f |
47 |
27 |
39 |
` |
147 |
67 |
103 |
g |
50 |
28 |
40 |
( |
150 |
68 |
104 |
h |
51 |
29 |
41 |
) |
151 |
69 |
105 |
i |
52 |
2a |
42 |
* |
152 |
6a |
106 |
j |
53 |
2b |
43 |
+ |
153 |
6b |
107 |
k |
54 |
2c |
44 |
, |
154 |
6c |
108 |
l |
55 |
2d |
45 |
- |
155 |
6d |
109 |
m |
56 |
2e |
46 |
. |
156 |
6e |
110 |
n |
57 |
2f |
47 |
/ |
157 |
6f |
111 |
o |
60 |
30 |
48 |
0 |
160 |
70 |
112 |
p |
61 |
31 |
49 |
1 |
161 |
71 |
113 |
q |
62 |
32 |
50 |
2 |
162 |
72 |
114 |
r |
63 |
33 |
51 |
3 |
163 |
73 |
115 |
s |
64 |
34 |
52 |
4 |
164 |
74 |
116 |
t |
65 |
35 |
53 |
5 |
165 |
75 |
117 |
u |
66 |
36 |
54 |
6 |
166 |
76 |
118 |
v |
67 |
37 |
55 |
7 |
167 |
77 |
119 |
w |
70 |
38 |
56 |
8 |
170 |
78 |
120 |
x |
71 |
39 |
57 |
9 |
171 |
79 |
121 |
y |
72 |
3a |
58 |
: |
172 |
7a |
122 |
z |
73 |
3b |
59 |
; |
173 |
7b |
123 |
{ |
74 |
3c |
60 |
< |
174 |
7c |
124 |
| |
75 |
3d |
61 |
= |
175 |
7d |
125 |
} |
76 |
3e |
62 |
> |
176 |
7e |
126 |
~ |
77 |
3f |
63 |
? |
177 |
7f |
127 |
del |
字符串与字节数组转换:(解决64位系统下Cookie传值乱码问题)
(1)字符串转换为字节数组
HttpCookie cookie = new HttpCookie("UserName");
cookie.Value = Convert.ToBase64String(System.Text.Encoding.GetEncoding("GB2312").GetBytes(reader["name"].ToString()));
(2)字节数组转换为字符串
Session["UserName"] = System.Text.Encoding.GetEncoding("GB2312").GetString(Convert.FromBase64String(Request.Cookies["UserName"].Value.ToString()));
异常:由于代码已经过优化或者本机框架位于调用堆栈之上,无法计算表达式的值
try
{
regcomm.ExecuteNonQuery();
Response.Redirect("regok.aspx");
}
catch{ Response.Redirect("regerr.aspx");}
解决方法:把Response.Redirect();语句从TRY中拿出
DataTable导入导出Excel
//导入
protected DataSet GetExcelContent(string filepath)
{
string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties='Excel 8.0;HDR=No;IMEX=1'";
System.Data.OleDb.OleDbConnection myConn = new System.Data.OleDb.OleDbConnection(strCon);
string strCom = "SELECT 0 as ID , ID as GoodsID,编码 as Code,名称 as Name,产品型号 as Model,单位 as Unit,账面库存 as BQ,0 as Quantity,'' as OI,货号 as ImgNum,'0' AS rIndex FROM [盘点单$]";
myConn.Open();
System.Data.OleDb.OleDbDataAdapter myCommand = new System.Data.OleDb.OleDbDataAdapter(strCom, myConn);
//创建一个DataSet对象
DataSet myDataSet = new DataSet();
//得到自己的DataSet对象
myCommand.Fill(myDataSet, "table1");
//关闭此数据链接
myConn.Close();
for (int i = 0; i < myDataSet.Tables["table1"].Rows.Count; i++)
{
myDataSet.Tables["table1"].Rows[i]["rIndex"] = i.ToString();
}
return myDataSet;
}
//导出
protected void lblUxToExcel_Click(object sender, EventArgs e)
{
StringWriter sw = new StringWriter();
sw.WriteLine("编号\t名称\t密码\t性别\tEmail\t城市\t地址\t登陆IP");
DataTable dt = userManager.FindAlluser();
foreach (DataRow dr in dt.Rows)
{
sw.WriteLine(dr["userId"] + "\t" + dr["userName"] + "\t" + dr["password"] + "\t" + dr["sex"] + "\t" + dr["email"] + "\t" + dr["city"] + "\t" + dr["address"] + "\t" + dr["loginIP"]);
}
sw.Close();
Response.AddHeader("Content-Disposition", "p_w_upload; filename=test.xls");
Response.ContentType = "application/ms-excel";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
Response.Write(sw);
Response.End();
}
DataTable排序
DataView dv = dt.DefaultView;
dv.Sort = "c1 Asc";
DataTable dt2 = dv.ToTable();
上传文件到数据库,然后下载文件
上传文件==>压缩文件为ZIP格式的压缩包==>将压缩包转换为二进制流==>插入数据库
上传:
HttpPostedFile UF = filePhoto.PostedFile;
byte[] File = new byte[UF.InputStream.Length];
UF.InputStream.Read(File, 0, (int)UF.InputStream.Length);
string fileType = UF.ContentType;
string fileTyep2 = UF.FileName.Substring(UF.FileName.LastIndexOf(".")+1);
long fileSize = UF.ContentLength;
Document.Web.Component.Editor ed = new Document.Web.Component.Editor();
long FileID = ed.SaveFile(DocID, File, fileType, fileSize, fileTyep2);
下载文件到选定的目录:<用户选中的磁盘文件>
从数据库中读取二进制流==>然后经过下面的方法进行下载操作:
下载:
byte[] FileRude = "从数据库读取的二进制流";
if (FileRude.Length != 0)
{
Response.Clear();
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AddHeader("content-disposition", "p_w_upload;filename=" + filename);
Response.BinaryWrite(FileRude);
Response.Flush();
Response.End();
}
int ImageId;//图片保存到数据库中的ID
string filetype ;//图片保存到数据库中的类型
byte[] img = "从数据库读取的二进制流";
if (img.Length>0)
{
Response.ContentType = filetype;
Response.AppendHeader("Content-Type", filetype);
Response.AddHeader("Content-Length", "" + img.Length);
Response.BinaryWrite(img); //输出
Response.Flush();
Response.End();
}
C# 图片上加文字
using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
namespace Xiaoyaosr.ZGCMisc.Web.Dzmp20100301
{
public partial class dzmp : System.Web.UI.Page
{
public string ShowImage;
protected void Page_Load(object sender, EventArgs e)
{
int jtid = Request["jt"] == null ? 0 : Convert.ToInt32(Request["jt"]);
int mpid = Request["mp"] == null ? 0 : Convert.ToInt32(Request["mp"]);
int lx = Request["lx"] == null ? 0 : Convert.ToInt32(Request["lx"]);
System.Data.DataRow row = Xiaoyaosr.ZGCMisc.Web.Common.GetMpInfo(jtid, mpid, lx).Rows[0];
System.Data.DataRow row2 = Xiaoyaosr.ZGCMisc.Web.Common.GetJtNames().Rows[0];
string str = @" "+row2["jtname"].ToString()+"(门票编号:"+row["mp"].ToString()+")"
+ " \r\n\r\n姓 名:" + row["xm"].ToString()
+ " \r\n电话号码:" + row["dh"].ToString()
+ " \r\n电子邮箱:" + row["yx"].ToString()
+ " \r\n活动时间:" + row2["jtdate"].ToString()
+ " \r\n活动地址:" + row2["jtaddr"].ToString();
Image img = GetImage(Server.MapPath("Images/ticket.jpg"), str);
string strSavePath=Server.MapPath("mpImages");
string strImageName="zgccyjt_" + row2["jtid"].ToString() + "_" + row["mp"].ToString() + ".jpg";
if (!Directory.Exists(strSavePath))
Directory.CreateDirectory(strSavePath);
string p_w_picpathName = Path.Combine(strSavePath, strImageName);
img.Save(p_w_picpathName, ImageFormat.Jpeg);
img.Dispose();
ShowImage = "";
}
private Image GetImage(string backgroundImagePath, string text)
{
int x = 10;
int y = 10;
Image img = Image.FromFile(backgroundImagePath);
Bitmap bmp = new Bitmap(img, img.Width, img.Height);
Graphics g = Graphics.FromImage(bmp);
//画图像
g.DrawImage(img, 0, 0);
//画字符
SolidBrush brush = new SolidBrush(Color.Black);
Font font = new Font("宋体", 14);
g.DrawString(text, font, brush, x, y);
//zx
brush.Dispose();
font.Dispose();
g.Dispose();
img.Dispose();
return bmp as Image;
}
}
}