0
我正在開發一個系統,在其中一個進程中,每天從Url下載一個.csv文件,只有這個文件帶有沒有標題的列,我想輸入每次完成下載文件時,都會在autmaticamenta列中顯示標題。在CSV文件中添加列標題
new row -------> new value - new value - new value
existing value - existing value - existing value
existing value - existing value - existing value
existing value - existing value - existing value
我的代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.IO;
using System.ComponentModel;
using System.Data;
using System.Globalization;
namespace CotacaoMoeda
{
class Program
{
static void Main(string[] args)
{
GetUrlCsv();
}
static void GetUrlCsv()
{
var dateString = DateTime.Now.ToString("yyyyMMdd");
//string dateString = "20160520";
WebClient wc = new WebClient();
wc.DownloadFile("http://www4.bcb.gov.br/Download/fechamento/" + dateString + ".csv", @"c:\temp\" + dateString + ".csv");
//Console.Write(dateString);
//String[] Values = File.ReadAllText(@"c:\temp\" + dateString + ".csv").Split(';');
string Caminho = @"c:\temp\" + dateString + ".csv";
StreamReader oStreamReader = new StreamReader(Caminho);
DataTable oDataTable = new DataTable();
int rowCount = 0;
string[] columnNames = null;
string[] oStreamDataValues = null;
while (!oStreamReader.EndOfStream)
{
string oStreamRowData = oStreamReader.ReadLine().Trim();
if (oStreamRowData.Length > 0)
{
oStreamDataValues = oStreamRowData.Split(';');
if (rowCount == 0)
{
rowCount = 1;
columnNames = oStreamDataValues;
foreach (string csvHeader in columnNames)
{
DataColumn oDataColum = new DataColumn(csvHeader.ToUpper(), typeof(string));
oDataColum.DefaultValue = string.Empty;
oDataTable.Columns.Add(oDataColum);
}
}
else
{
DataRow oDataRow = oDataTable.NewRow();
for (int i = 0; i < columnNames.Length; i++)
{
oDataRow[columnNames[i]] = oStreamDataValues[i] == null ? string.Empty : oStreamDataValues[i].ToString();
}
oDataTable.Rows.Add(oDataRow);
}
}
}
oStreamReader.Close();
oStreamReader.Dispose();
foreach (DataRow Dr in oDataTable.Rows)
{
string RowValues = string.Empty;
foreach (string csvColumns in columnNames)
{
RowValues += csvColumns + "=" + Dr[csvColumns].ToString() + " ";
}
Console.Write(RowValues);
}
Console.ReadKey();
Console.ReadLine();
}
}
}
我覺得OP一直在尋找一個綱領性的解決方案 –
@ AlexW沒錯!我需要程序化,它會創建一個常規服務。 –
看代碼@IgorLessa –