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++;
}