C# asp.net将CSV字符串转换为字符串[]
是否有一种简单的方法将字符串从csv格式转换为字符串[]或列表 我可以保证数据中没有逗号。string[]splitString=origString.Split(',');C# asp.net将CSV字符串转换为字符串[],c#,string,csv,C#,String,Csv,是否有一种简单的方法将字符串从csv格式转换为字符串[]或列表 我可以保证数据中没有逗号。string[]splitString=origString.Split(','); CsvString.split(','); (以下评论未由原回答者添加) 请记住,此答案解决了保证数据中没有逗号的特定情况。获取所有行的字符串[]: string[] lines = System.IO.File.ReadAllLines("yourfile.csv"); 然后循环并拆分这些行(这很容易出错,因为它不检
CsvString.split(',');
(以下评论未由原回答者添加)
请记住,此答案解决了保证数据中没有逗号的特定情况。获取所有行的字符串[]:
string[] lines = System.IO.File.ReadAllLines("yourfile.csv");
然后循环并拆分这些行(这很容易出错,因为它不检查引号分隔字段中的逗号):
请注意,Split()使用一个字符数组进行拆分。如果您想要强大的CSV处理,请查看如果您想要使用嵌入逗号的带引号的元素,特别是当它们与非带引号的字段混合时,没有一种简单的方法可以做到这一点
separationChar[] = {';'}; // or '\t' ',' etc.
var strArray = strCSV.Split(separationChar);
您可能还希望将这些行转换为由列名键入的字典
我的代码有几百行
我认为网络上有一些例子,开源项目等等。试试:
Regex rex = new Regex(",(?=([^\"]*\"[^\"]*\")*(?![^\"]*\"))");
string[] values = rex.Split( csvLine );
来源:一些CSV文件的值周围有双引号和逗号。因此,有时您可以拆分此字符串文字:“,”带有引号字段的Csv文件不是Csv文件。在另存为中选择“Csv”时,更多的内容(Excel)输出时不带引号,而不是带引号 如果你想要一个你可以使用,免费,或承诺,这里的我也做IDataReader/记录。它还使用DataTable定义/转换/强制执行列和DbNull 它不做引号。。然而几天前我把它扔在一起搔痒 忘记分号:很好的链接。谢谢
cfeduke:感谢您提供Microsoft.VisualBasic.FileIO.TextFieldParser的提示。今晚将进入CsvDataReader。String.Split不会阻止它,但是Regex.Split可能会-尝试以下方法:
using System.Text.RegularExpressions;
string[] line;
line = Regex.Split( input, ",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
其中“输入”是csv行。这将处理带引号的分隔符,并将返回一个表示行中每个字段的字符串数组。您可以查看如何将Microsoft.VisualBasic程序集与
Microsoft.VisualBasic.FileIO.TextFieldParser
它使用引号处理CSV(或任何分隔符)。我最近发现它很方便。试试这个
static IEnumerable<string> CsvParse(string input)
{
// null strings return a one-element enumeration containing null.
if (input == null)
{
yield return null;
yield break;
}
// we will 'eat' bits of the string until it's gone.
String remaining = input;
while (remaining.Length > 0)
{
if (remaining.StartsWith("\"")) // deal with quotes
{
remaining = remaining.Substring(1); // pass over the initial quote.
// find the end quote.
int endQuotePosition = remaining.IndexOf("\"");
switch (endQuotePosition)
{
case -1:
// unclosed quote.
throw new ArgumentOutOfRangeException("Unclosed quote");
case 0:
// the empty quote
yield return "";
remaining = remaining.Substring(2);
break;
default:
string quote = remaining.Substring(0, endQuotePosition).Trim();
remaining = remaining.Substring(endQuotePosition + 1);
yield return quote;
break;
}
}
else // deal with commas
{
int nextComma = remaining.IndexOf(",");
switch (nextComma)
{
case -1:
// no more commas -- read to end
yield return remaining.Trim();
yield break;
case 0:
// the empty cell
yield return "";
remaining = remaining.Substring(1);
break;
default:
// get everything until next comma
string cell = remaining.Substring(0, nextComma).Trim();
remaining = remaining.Substring(nextComma + 1);
yield return cell;
break;
}
}
}
}
静态IEnumerable CsvParse(字符串输入)
{
//null字符串返回包含null的单元素枚举。
如果(输入==null)
{
收益返回空;
屈服断裂;
}
//我们将“吃”一点绳子,直到它消失。
剩余字符串=输入;
而(剩余长度>0)
{
if(剩余的.StartsWith(“\”)//处理引号
{
剩余=剩余。子字符串(1);//传递初始引号。
//查找结束引用。
int endQuotePosition=剩余的.IndexOf(“\”);
开关(endQuotePosition)
{
案例1:
//未关闭的报价。
抛出新ArgumentOutOfRangeException(“未关闭的报价”);
案例0:
//空话
收益率回报率“;
剩余=剩余。子字符串(2);
打破
违约:
字符串引号=剩余的.Substring(0,endQuotePosition).Trim();
剩余=剩余。子字符串(endQuotePosition+1);
收益回报报价;
打破
}
}
else//处理逗号
{
int-nextComma=remaining.IndexOf(“,”);
交换机(nextComma)
{
案例1:
//没有更多的逗号--读到结尾
剩余收益率。Trim();
屈服断裂;
案例0:
//空牢房
收益率回报率“;
剩余=剩余。子字符串(1);
打破
违约:
//在下一个逗号之前拿到所有东西
字符串单元格=剩余的.Substring(0,nextComma.Trim();
剩余=剩余。子字符串(nextComma+1);
产量返回单元;
打破
}
}
}
}
使用cfeduke建议的TextFieldParser进行更新
离暴露分隔符/修剪空间/键入ig只有几步之遥,你只需要窃取代码。我已经在选项卡上拆分了,所以这为我带来了窍门:
public static string CsvToTabDelimited(string line) {
var ret = new StringBuilder(line.Length);
bool inQuotes = false;
for (int idx = 0; idx < line.Length; idx++) {
if (line[idx] == '"') {
inQuotes = !inQuotes;
} else {
if (line[idx] == ',') {
ret.Append(inQuotes ? ',' : '\t');
} else {
ret.Append(line[idx]);
}
}
}
return ret.ToString();
}
公共静态字符串CsvToTabDelimited(字符串行){
var ret=新的StringBuilder(线条长度);
bool-inQuotes=false;
for(intidx=0;idx
如果数据中有逗号,则使用String.split(“,”);如果数据包含带空格的逗号,那么csv在存储和传输数据时是一个糟糕的选择。我想我们正在寻找一行,csv到值集数组。我认为这个问题是不明确的。如何从数据中的逗号和分隔数据的逗号中分离出来?因为这个问题n最终会被谷歌为这些关键词编入索引。如果在顶部有一个更完整的答案会更好。我想如果你想问一个不同的问题(或者同一个问题有更多细节),你应该这样做,而不是劫持这一个,让它看起来像是原始提问者的问题的答案是错误的。确实,我可以保证数据中没有逗号,所以我的问题的可接受答案是我接受的,string[]splitString=origString.Split(',');
Regex rex = new Regex(",(?=([^\"]*\"[^\"]*\")*(?![^\"]*\"))");
string[] values = rex.Split( csvLine );
using System.Text.RegularExpressions;
string[] line;
line = Regex.Split( input, ",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
Microsoft.VisualBasic.FileIO.TextFieldParser
static IEnumerable<string> CsvParse(string input)
{
// null strings return a one-element enumeration containing null.
if (input == null)
{
yield return null;
yield break;
}
// we will 'eat' bits of the string until it's gone.
String remaining = input;
while (remaining.Length > 0)
{
if (remaining.StartsWith("\"")) // deal with quotes
{
remaining = remaining.Substring(1); // pass over the initial quote.
// find the end quote.
int endQuotePosition = remaining.IndexOf("\"");
switch (endQuotePosition)
{
case -1:
// unclosed quote.
throw new ArgumentOutOfRangeException("Unclosed quote");
case 0:
// the empty quote
yield return "";
remaining = remaining.Substring(2);
break;
default:
string quote = remaining.Substring(0, endQuotePosition).Trim();
remaining = remaining.Substring(endQuotePosition + 1);
yield return quote;
break;
}
}
else // deal with commas
{
int nextComma = remaining.IndexOf(",");
switch (nextComma)
{
case -1:
// no more commas -- read to end
yield return remaining.Trim();
yield break;
case 0:
// the empty cell
yield return "";
remaining = remaining.Substring(1);
break;
default:
// get everything until next comma
string cell = remaining.Substring(0, nextComma).Trim();
remaining = remaining.Substring(nextComma + 1);
yield return cell;
break;
}
}
}
}
public static string CsvToTabDelimited(string line) {
var ret = new StringBuilder(line.Length);
bool inQuotes = false;
for (int idx = 0; idx < line.Length; idx++) {
if (line[idx] == '"') {
inQuotes = !inQuotes;
} else {
if (line[idx] == ',') {
ret.Append(inQuotes ? ',' : '\t');
} else {
ret.Append(line[idx]);
}
}
}
return ret.ToString();
}