·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设开发 >> ASP.NET网站开发 >> .NET中的CSV导入导出(实例)

.NET中的CSV导入导出(实例)

作者:佚名      ASP.NET网站开发编辑:admin      更新时间:2022-07-23

.NET中的CSV导入导出(实例)

导入代码,从csv文件得到datatable ///<summary>///GetDataFromCsvFile///(ThroughStreamReader)///</summary>///<returns></returns>PRivateboolGetData(StreaminputStream,outstringerrMessage,outDataTabledtFile){errMessage=String.Empty;dtFile=newDataTable();

//this.FileUploadImport.PostedFile.InputStream.CanSeek;//StreamReadersr=newStreamReader(this.FileUploadImport.PostedFile.InputStream);//updatebyhwx11/12/2010StreamReadersr=newStreamReader(inputStream);intiColumnCount=19;//thecolumncountinthefileintiRow=1;//therownumberisbeingreadintiColumn=0;//thecolumnnumberisbeingreadstringstrStandardTitle=string.Empty;//thetitleasitis//readtitlerowstringstrTitle=sr.ReadLine();//string[]strRowTitle=strTitle.Split(newchar[]{','});string[]strRowTitle=newstring[iColumnCount];stringstrCharTitle;intiCellNumberTitle=0;boolblnQuoteTitle=false;for(inti=0;i<strTitle.Length;i++){strCharTitle=strTitle.Substring(i,1);if(strCharTitle==",")//","istheseperationsymbolofcsvfile,{if(!blnQuoteTitle){iCellNumberTitle++;//outofthe""range,","istheseperationsymbolif(iCellNumberTitle>=iColumnCount)//toomanycolumninthisline{break;}}else{strRowTitle[iCellNumberTitle]+=strCharTitle;}}elseif(strCharTitle=="\"")//"\""isthetransfersymbolofcsvfile,{blnQuoteTitle=!blnQuoteTitle;if(blnQuoteTitle&&i>0&&strTitle.Substring(i-1,1)=="\"")//inthe""rangeandthereisantransfersymbolbefore{strRowTitle[iCellNumberTitle]+=strCharTitle;}}else{strRowTitle[iCellNumberTitle]+=strCharTitle;}}//readthecontentif(strRowTitle.Length==iColumnCount){foreach(stringstrCellinstrRowTitle){iColumn++;if(strCell.Trim()!=string.Empty){dtFile.Columns.Add(strCell);//addnewcolumnwithnametothedatatable}else//fileerror:blanktitle{errMessage+="Thecell"+iColumn.ToString()+"isblankintheheaderrow.\r\n";}}if(dtFile.Columns.Count==iColumnCount)

//makesurethatnoblankheaderorerrorheader{//readcontentrowstringstrLine;while(!sr.EndOfStream){iRow++;iColumn=0;DataRowdr=dtFile.NewRow();strLine=sr.ReadLine();//readcsvfilelinebylinestring[]strRow=newstring[iColumnCount];stringstrChar;intiCellNumber=0;boolblnQuote=false;//whetherinthe""rangefor(inti=0;i<strLine.Length;i++){strChar=strLine.Substring(i,1);if(strChar==",")//","istheseperationsymbolofcsvfile,{if(!blnQuote){iCellNumber++;//outofthe""range,","istheseperationsymbolif(iCellNumber>=iColumnCount)//toomanycolumninthisline{break;}}else{strRow[iCellNumber]+=strChar;}}elseif(strChar=="\"")//"\""isthetransfersymbolofcsvfile,{blnQuote=!blnQuote;if(blnQuote&&i>0&&strLine.Substring(i-1,1)=="\"")//inthe""rangeandthereisantransfersymbolbefore{strRow[iCellNumber]+=strChar;}}else{strRow[iCellNumber]+=strChar;}}if(iCellNumber+1==iColumnCount){foreach(stringstrCellinstrRow){iColumn++;if(strCell!=null&&strCell.Trim()!=string.Empty){dr[strRowTitle[iColumn-1]]=strCell.Trim();}else//fileerror:blankcell{dr[strRowTitle[iColumn-1]]=String.Empty;//errMessage+="Thecolumn\""+strRowTitle[iColumn-1]+"\"isblankinrow"+iRow.ToString()+".\r\n";}}}else//fileerror:thecolumncountofcurrentrowdonotequaltotitle's{errMessage+="Therearemoreorlesscellsthantitlerowintherow"+iRow.ToString()+".\r\n";}dtFile.Rows.Add(dr);}}}else//fileerror:thecountofcolumnsinthefiledon'tequalitshouldbe{errMessage+="Thereareanincorrectnumberofcolumnsintheheaderrowcomparedtothetemplatefile.\r\n";}sr.Close();sr.Dispose();errMessage=errMessage.Replace("\r\n","<br>");returnerrMessage==String.Empty?true:false;}///<summary>///Getdatasetfromcsvfile.///</summary>///<paramname="filepath">http://www.nuoya118.com</param>///<paramname="filename"></param>///<returns>DataSet</returns>privateDataSetGetDatasetFromCsv(stringfilepath,stringfilename){stringstrconn=@"driver={microsofttextdriver(*.txt;*.csv)};dbq=";strconn+=filepath;//filepath,forexample:c:\strconn+=";extensions=asc,csv,tab,txt;";OdbcConnectionobjconn=newOdbcConnection(strconn);DataSetdscsv=newDataSet();try{stringstrsql="select*from"+filename;//filename,forexample:1.csvOdbcDataAdapterodbccsvdataadapter=newOdbcDataAdapter(strsql,objconn);odbccsvdataadapter.Fill(dscsv);returndscsv;}catch(Exceptionex){throwex;}}

csv导出代码

///<summary>///ExporttoCsvFilefromdataset///</summary>///<paramname="src"></param>///<paramname="folderName">folderName</param>///<paramname="strFileName">strFileName</param>///<returns></returns>publicboolExportToCsv(DataSetsrc,stringfolderName,stringstrFileName){stringcsv=String.Empty;StreamWriterwriter=null;stringfileName=Server.MapPath("/")+folderName+"\\"+strFileName;try{if(src==null||src.Tables.Count==0)thrownewException("datasetisnullorhasnottableindataset");for(inti=0;i<src.Tables.Count;i++){if(i>0)fileName=fileName.Substring(0,fileName.IndexOf('.'))+i+fileName.Substring(fileName.IndexOf("."));writer=newStreamWriter(fileName);DataTabledt=src.Tables[i];StringBuildersb=newStringBuilder();for(intj=0;j<dt.Columns.Count;j++){stringcolName=dt.Columns[j].ColumnName;if(colName.IndexOf(',')>-1)colName=colName.Insert(0,"\"").Insert(colName.Length+1,"\"");sb.Append(colName);if(!colName.Equals(""))if(j!=dt.Columns.Count-1)sb.Append(",");}writer.WriteLine(sb.ToString());sb=newStringBuilder();stringtemp="";for(intj=0;j<dt.Rows.Count;j++){DataRowdr=dt.Rows[j];for(intk=0;k<dt.Columns.Count;k++){objecto=dr[k];if(o!=null)temp=o.ToString();if(temp.IndexOf(',')>-1)temp=temp.Insert(0,"\"").Insert(temp.Length+1,"\"");sb.Append(temp);if(k!=dt.Columns.Count-1)sb.Append(",");}writer.WriteLine(sb.ToString());sb=newStringBuilder();csv=sb.ToString();}writer.Close();}stringstrFilePath=Server.MapPath("/")+folderName;if(!Directory.Exists(strFilePath)){Directory.CreateDirectory(strFilePath);}strFullFileName=Server.MapPath("/")+folderName+"\\"+fileName;//FullFileName=Server.MapPath(FileName);//FileNameFileInfoDownloadFile=newFileInfo(strFullFileName);if(DownloadFile.Exists){Response.Clear();Response.ClearHeaders();Response.Buffer=false;Response.ContentType="application/octet-stream";//Response.AppendHeader("Content-Disposition","attachment;filename="+HttpUtility.UrlEncode(DownloadFile.FullName,System.Text.Encoding.ASCII));Response.AppendHeader("Content-Disposition","attachment;filename="+HttpUtility.UrlEncode(fileName,System.Text.Encoding.ASCII));Response.AppendHeader("Content-Length",DownloadFile.Length.ToString());Response.WriteFile(DownloadFile.FullName);Response.Flush();//Response.End();}else{//notexistthrownewException("Exportcsvfiledoesnotexist!");}}catch(Exceptionex){thrownewException("Savecsverror",ex);}finally{if(writer!=null)writer.Close();}returntrue;}///<summary>///ListtoDataTable///</summary>///<paramname="entitys">entityslist</param>///<returns></returns>publicDataTableListToDataTable(List<T>entitys){if(entitys==null||entitys.Count<1){thrownewException("listisnull");}//getfirstPropertieTypeentityType=entitys[0].GetType();PropertyInfo[]entityProperties=entityType.GetProperties();//DataTablestructure//DataTabledt=newDataTable();for(inti=0;i<entityProperties.Length;i++){//dt.Columns.Add(entityProperties[i].Name,entityProperties[i].PropertyType);dt.Columns.Add(entityProperties[i].Name);}//addentitytoDataTableforeach(objectentityinentitys){//checktypeif(entity.GetType()!=entityType){thrownewException("typenotsame");}object[]entityValues=newobject[entityProperties.Length];for(inti=0;i<entityProperties.Length;i++){entityValues[i]=entityProperties[i].GetValue(entity,null);}dt.Rows.Add(entityValues);}returndt;}