C#的CSV文件导入导出

1. asp.net的导出:

<pre name="code" class="csharp">StringBuilder DATA = new StringBuilder("");

Response.Clear();
Response.ContentType = "text/plain; charset=Shift_JIS";
Response.AddHeader("content-disposition", "attachment; filename=" + filename + ".csv");
...  //从DB中取得Data
DATA.Append(...);	//将Data写入DATA,CSV文件要以”,"分割

Response.Write(DATA.ToString());
Response.End();

2.WinForm的导出:
... //取得保存路径
... //从DB中取得Data
... //同1,将以","分割的数据写入StringBuilder
StreamWriter sw = new StreamWriter(exportPath, false, Encoding.GetEncoding("shift_jis"));
sw.Write(stringData.ToString());

3.asp.net的导入:

 
HtmlInputFile txtHtmlInputFile = txtFile; //txtFile是画面中的input控件中取得的文件
System.IO.Stream inStream = txtHtmlInputFile.PostedFile.InputStream;

//DataStream读取
Byte[] mstreamBackUp = new Byte[inStream.Length];
inStream.Read(mstreamBackUp, 0, int.Parse(inStream.Length.ToString()));
//用来Check的Stream
MemoryStream chkStream = new MemoryStream(mstreamBackUp);

System.Text.Encoding enc = System.Text.Encoding.Default;
TextFieldParser parser = new TextFieldParser(chkStream, enc);
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimitens(",");
parser.TrimWhiteSpace = false;

while(!parser.EndOfData){
	String strOrgText = parser.ReadFields();	//读取一行
	String[] strAryText = new String[strOrgText.Length];
	int i=0;
	foreach(String field in strOrgText){
		strArgText[i] = field;
		i++;
	}
	...	//执行各种Check
	...	//向DB插入数据
}

parser.Close();
parser = null;

4.WinForm的导入:
Private sctTeam[] ImpTeamAry;	//保存用的导入数据
Private struct sctTeam{
	public String itemA;
	...	//B
	...	//C
}

//ImpTeamAry中写入CSV数据
//用OpenFileDialog取得CSV文件
String strFileName = openFileDialog1.FileName;
StreamReader sr = new StreamReader(strFileName, System.Text.EncodingDefault);
String strText = sr.ReadToEnd();	//读到最后
If (strText.Length <= 0 || strText.SubString(0, 1) ! "\""){
	...	//读取失败信息
}
sr.Close();
strText.Replace("\r", "");	//删除换行
String[] strTextAry = strText.Split('\n');
if (strTextAry.Length < 1){
	...	//读取失败信息
}

//定义和memory
ImpTeamAry = new sctTeam[strTextAry.Length];
for(int i=0; i<strTextAry.Length; i++){
	ImpTeamAry[i] = new sctTeam();	//确保Memory
}

//取得数据
int j=0;	//数据数组Index
for (int ii=0; ii<=strTextAry.Length-1; ii++){
	if(strTextAry[ii].ToString().Trim().Length == 0)
		continue;
	//各项目取得
	String[] strAryField = strTextAry[ii].Split(',');
	ImpTeamAry[j].itemA = strAryField[0].ToString().Replace("\"", "");
	...	//B
	...	//C
	j++;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值