我必须逐行读取现有文件“operativedata.txt”的内容,并逐行将此数据写入excelsheet“datawarehouse.csv”。文件“operativedata.txt”的内容如下图所示(operativedata.txt)):
必须以与datawarehouse.csv不同的方式将operatedata.txt中的数据写入。 它必须在csv文件中看起来像这样:
“date; time; randomvalue \ n”\ n表示在这三行之后返回
这种格式必须在datawarehouse.csv文件中写入(全部10秒)。它应该在最后看起来像这样:datawarehouse.csv
生成datawarehouse.csv的代码:
using System;
using System.IO;
using System.Threading;
namespace etltxt2csv
{
class Program
{
string[]content;//Array for reading each line of the file operativedata.txt
public void loop()
{
content = File.ReadAllLines(@"C:\ETL-Process\operativedata.txt");//File to be Read
while (true)
{
for (int i = 0; i < content.Length; i++)
{
Thread.Sleep(10000);
File.AppendAllText(@"C:\ETL-Process\datawarehouse.csv", content[i] + ";" + "\n");
Console.WriteLine(content[i]);
}
}
}
static void Main(string[] args)
{
Program a= new Program();
a.loop();
}
}
}
使用以下代码创建了operativedata.txt:
using System;
using System.Threading;
using System.IO;
namespace createData
{
class Program
{
string file, date, time;
int randomValue;
public void createFile()
{
file = @"C:\ETL-Process\operativedata.txt";
date = DateTime.Now.ToString("yyMMdd");
time = DateTime.Now.ToString("HHmmss");
Random random = new Random();
while (true)
{
randomValue = random.Next(200);
Thread.Sleep(10000);
File.AppendAllText(file, "\r\n" +date + "\r\n" + time + "\r\n" + randomValue);
}
}
static void Main(string[] args)
{
Program a = new Program();
a.createFile();
}
}
}
我需要在etltxt2csv的代码中进行哪些更改才能以这种方式编写数据:
“date; time; randomvalue \ n”(总是前三行中接下来的三行返回\ n)
进入文件datawarehouse.csv?
当我执行此处列出的etltxt2代码时,我的excel文件的输出在图片中没有像上面那样进行转换(datawarehouse.csv)
答案 0 :(得分:1)
您需要从.txt文件中读取三行,并将它们组合成一行以进行输出:
using (var input = File.OpenText(txt_file_name))
{
using (var output = File.CreateText(csv_file_name))
{
var date = input.ReadLine();
var time = input.ReadLine();
var random = input.ReadLine();
output.WriteLine("{0};{1};{2}", date, time, random);
}
}
var
是一个关键字,告诉编译器推断出类型。例如,当你写:
var input = File.OpenText(filename);
编译器知道File.OpenText
返回StreamReader
,因此会自动input
输入StreamReader
。这是与上面相同的代码,var
替换为实际类型:
using (StreamReader input = File.OpenText(txt_file_name))
{
using (StreamWriter output = File.CreateText(csv_file_name))
{
string date = input.ReadLine();
string time = input.ReadLine();
string random = input.ReadLine();
output.WriteLine("{0};{1};{2}", date, time, random);
}
}
答案 1 :(得分:0)
与Jim Mischel同意,输出文件中每行需要读取3行。
如果你保持相同的API调用,这就是循环的样子:
(注意:使用Jim Mischel的API调用更好的内存使用和性能......)
for (int i = 0; i + 2 < content.Length; i += 3)
{
// Console.WriteLine(content[i] + ";" + content[i+1] + ";" + content[i+2]);
File.AppendAllText(
@"C:\ETL-Process\datawarehouse.csv",
content[i + 0] + ";"
+ content[i + 1] + ";"
+ content[i + 2] + "\n"
);
}