public static double[] GetColumn(double[][] data, int i)//取得二维数组第i列,从0开始
{
Listlist = new List ();
foreach (double[] line in data)
{
if (line.Length > i)
list.Add(line[i]);
}
return list.ToArray();
}
public static double[][] ReadFileToArray(string file)//读入文件至二维交错数组
{
string[] line = File.ReadAllText(file).Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
if(line.Length>0)
{
double[][] result = new double[line.Length - 1][];
int count = -1;
double temp = 0f;
foreach (string str in line)//处理每一行
{
if (count < 0) { count++; continue; }//首行不处理
string[] part = str.Split(new char[] { ',', ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
result[count] = new double[part.Length];
if (part.Length > 0)
{
int subcount = 0;
foreach (string s in part)//处理每行中数据
{
if (double.TryParse(s, out temp))//错误处理,防止行中错误数字或分隔符
result[count][subcount] = temp;
subcount++;
}
}
count++;
}
return result;
}
return null;
}
//示例
double[][] data = ReadFileToArray(@"d:\1.txt");//取出完整数组
if(data!=null)
double[] col = GetColumn(data, 1);//取得第二列
int k = 0;//读取第几列的数据,默认
string strResult = "";//读取的结果
var filepath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "1.dat");
if (File.Exists(filepath))
{
using (StreamReader sw = new StreamReader(filepath))
{
string strLine1 = sw.ReadLine(); //读取第一行,不做处理
string strLine = sw.ReadLine();
while (!string.IsNullOrEmpty(strLine))
{
var array = strLine.Split(',');
if (array.Length > 0)
{
strResult += array[k];
strResult += ",";
}
strLine = sw.ReadLine();
}
}
}
FileStream fstream = new FileStream(filepath, FileMode.Open,FileAccess.ReadWrite);
StreamReader fileReader = new StreamReader(fstream);
List
string strLine = "";
while (strLine != null)
{
strLine = fileReader.ReadLine();
if (strLine != null && strLine.Length > 0)
{
ls.Add(strLine.Split(','));
}
}
fileReader.Close();
//下面组建你要存放数据的Table,我以前的数据第一行是列名所以下编码,这里你自己根据需要来改写
DataTable dt = new DataTable();
for (int i = 1; i < 18; i++)
{
DataColumn newColumn = new DataColumn(“列”+i);
dt.Columns.Add(newColumn);
}
for (int i = 1; i < ls.Count; i++)
{
int j = 0;
DataRow mydr; mydr = dt.NewRow();
int intColCount = dt.Columns.Count;
foreach (string str in ls[i])
{
//如果只需要某几列自己在这里加判断吧
mydr[j] = str; j++;
}
dt.Rows.Add(mydr);
}
这样dt就是所有的数据吧,如果只要其中一部分,自己再简单改一下吧!
你好!!
你把文件贴出来一部分内容,不要图片,发私信也行