在CSV文件中填充数据集我想读取CSV文件的内容并创建数据集。我是这样想的:varlines=File.ReadAllLines("test.csv").Select(a=>a.Split(';'));数据集ds=new数据集();ds.load(线);但显然这是不正确的。您需要针对CSV文件运行SELECT语句以填充数据集:编辑:这是来自http://carllbrown.blogspot.co.uk/2007/09/populate-dataset-from-csv-delimited_18.html的一些示例代码stringFileName=...OleDbConnectionconn=newOleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;DataSource="+Path.GetDirectoryName(FileName)+";ExtendedProperties="Text;HDR=YES;FMT=Delimited"");conn.Open();OleDbDataAdapter适配器=newOleDbDataAdapter("SELECT*FROM"+Path.GetFileName(FileName),conn);DataSetds=newDataSet("Temp");适配器。填充(ds);康涅狄格州关闭();您需要添加对Microsoft.VisualBasic.dll的引用才能使用TextFieldParser类。privatestaticDataTableGetDataTabletFromCSVFile(stringcsv_file_path){DataTablecsvData=newDataTable();尝试使用(TextFieldParsercsvReader=newTextFieldParser(csv_file_path)){csvReader.SetDelimiters(新字符串[]{“,”});csvReader.HasFieldsEnclosedInQuotes=true;字符串[]colFields=csvReader.ReadFields();foreach(colFields中的字符串列){DataColumndatecolumn=newDataColumn(column);日期列.AllowDBNull=true;csvData.Columns.Add(日期列);}while(!csvReader.EndOfData){string[]fieldData=csvReader.ReadFields();//Makingemptyvalueasnullfor(inti=0;i有关详细信息,请参阅此文章:http://www.morgantechspace.com/2013/08/how-to-read-data-from-csv-file-in-c.html您可以使用像快速CSV阅读器这样的库usingSystem.IO;usingLumenWorks.Framework.IO.Csv;voidReadCsv(){//打开文件“data.csv”这是一个带有标题的CSV文件使用(CsvReadercsv=newCsvReader(newStreamReader("data.csv"),true)){myDataRepeater.DataSource=csv;myDataRepeater.DataBind();}}逗号(,)本规范中解决的问题即使在单元格之间添加逗号(,)也能正常工作读取CSV文件数据表dtDataSource=newDataTable();string[]fileContent=File.ReadAllLines(@"..\Book1.csv");if(fileContent.Count()>0){//动态创建数据表列string[]columns=fileContent[0].Split(',');for(inti=0;ix=='"')%2==0))//检查字符串是否包含偶数个双引号{realRowData[K]=quotesLogic((rowData[j]));}elseif((rowData[j].Count(x=>x=='"')%2!=0))//如果双引号的个数是奇数{intc=rowData[j].Count(x=>x=='"');v=j;while(c%2!=0)//遍历所有下一个数组单元格,直到它使双引号为偶数。{collaboration.Append(rowData[j]+",");j++;c+=rowData[j].Count(x=>x=='"');}collaboration.Append(rowData[j]);realRowData[K]=quotesLogic(collaboration.ToString());}else{继续;}}#endregiondtDataSource。Rows.Add(realRowData);}if(dtDataSource!=null){//dataGridView1=newDataGridView();dataGrid1.ItemsSource=dtDataSource.DefaultView;}}}方法需要添加:stringquotesLogic(stringcollaboration){StringBuilderafter=newStringBuilder(collaboration);if(after.ToString().StartsWith(""")&&after.ToString().EndsWith("""))//删除第一个和最后一个引号,因为它们是系统生成的{after.Remove(0,1);after.Remove(after.Length-1,1);intcount=after.Length-1;//事实:如果您尝试在Excel的单元格中添加双引号。它将将该引用保存为2倍DoubleQuote(Like""),这意味着第一个DoubleQuote是向CPU发出指令,下一个DoubleQuote不是系统生成的。while(count>0)//此循环找到两次插入2个DoubleQuotes并将它们中和为OneDoubleQuote。{if(after[count]=='"'&&after[count-1]=='"'){after.Remove(count,1);}数数-;}}返回after.ToString();}如果您只是想快速创建一个填充了CSV文件在(或直接从Excel中粘贴)示例数据来玩DataTable或原型,然后您可以使用我的ShanCarter先生的数据转换器-我最近添加了此功能以将逗号和制表符分隔的数据输出到C#DataTablehttp://thdoan.github.io/mr-data-converter/我在下面写了五种方法来将Csv文件转换为DataTable。它们在设计时考虑了可选引号(例如“符号”),并且在不使用额外库的情况下尽可能多样化:publicstaticDataTableGetDataTabletFromCSVFile(stringfilePath,boolisHeadings){尝试{使用(TextFieldParserTextFieldParser=newTextFieldParser(filePath)){if(isHeadings){MethodResult=GetDataTableFromTextFieldParser(TextFieldParser);}else{MethodResult=GetDataTableFromTextFieldParserNoHeadings(TextFieldParser);方法结果;}publicstaticDataTableGetDataTableFromCsvString(stringcsvBody,boolisHeadings){DataTableMethodResult=null;尝试{MemoryStreamMemoryStream=newMemoryStream();StreamWriterStreamWriter=newStreamWriter(MemoryStream);StreamWriter.Write(csvBolush););内存流.Position=0;使用(TextFieldParserTextFieldParser=newTextFieldParser(MemoryStream)){if(isHeadings){MethodResult=GetDataTableFromTextFieldParser(TextFieldParser);}埃尔斯e{MethodResult=GetDataTableFromTextFieldParserNoHeadings(TextFieldParser);}}}catch(Exceptionex){ex.HandleException();}返回方法结果;}publicstaticDataTableGetDataTableFromRemoteCsv(stringurl,boolisHeadings){DataTableMethodResult=null;尝试{HttpWebRequesthttpWebRequest=(HttpWebRequest)WebRequest.Create(url);HttpWebResponsehttpWebResponse=(HttpWebResponse)httpWebRequest.GetResponse();StreamReaderStreamReader=newStreamReader(httpWebResponse.GetResponseStream());使用(TextFieldParserTextFieldParser=newTextFieldParser(StreamReader)){if(isHeadings){MethodResult=GetDataTableFromTextFieldParser(TextFieldParser);}else{MethodResult=GetDataTableFromTextFieldParserNoHeadings(TextFieldParser);}}}catch(Exceptionex){ex.HandleException();}返回方法结果;}privatestaticDataTableGetDataTableFromTextFieldParser(TextFieldParsertextFieldParser){DataTableMethodResult=null;尝试{textFieldParser.SetDelimiters(新字符串[]{“,”});textFieldParser.HasFieldsEnclosedInQuotes=true;字符串[]ColumnFields=textFieldParser.ReadFields();DataTabledt=newDataTable();foreach(ColumnFields中的字符串ColumnField){DataColumnDataColumn=newDataColumn(ColumnField);DataColumn.AllowDBNull=true;dt.Columns.Add(DataColumn);}while(!textFieldParser.EndOfData){string[]Fields=textFieldParser.ReadFields();for(inti=0;i如果像我一样从ReportingServices保存,那么你应该这样使用它:Warning[]warnings;string[]streams;stringmimeType;stringencoding;stringfilenameExtension;byte[]bytes=rvMain.ServerReport.Render("csv",null,出mimeType,出编码,出filenameExtension,出streamids,出警告);stringCsvBody=System.Text.Encoding.UTF8.GetString(bytes);DataTabledt=GetDataTableFromCsvString(CsvBody,true);否则,你需要做的就是:boolIsHeadings=true;//数据是否包含标题行?DataTabledt=GetDataTableFromCsvString(CsvBody,IsHeadings);或直接从csv文件使用boolIsHeadings=true;//数据是否包含标题行?DataTabledt=GetDataTabletFromCsvFile(FilePath,IsHeadings)或使用远程存储的csv文件boolIsHeadings=true;//数据是否包含标题行?DataTabledt=GetDataTabletFromRemoteCsv(Url,IsHeadings)数据集是DataTables的集合,所以创建一个如下:对大家有用,需要详细了解C#学习教程。希望大家多多关注---DataSetds=newDataSet();ds.Tables.Add(dt);本文收集自网络,不代表立场。如涉及侵权,请点击维权联系管理员删除如需转载请注明出处:
