Обычно я получаю файл Excel от пользователя, который успешно его проанализировал. Этот шаг сделан, теперь мне просто нужно добавить заголовок. Например, Заголовок1, Заголовок2, Заголовок3, Заголовок4, Заголовок5. У меня есть пять столбцов в CSV-файле. Может кто-нибудь помочь, пожалуйста?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.OleDb;
using System.Diagnostics;
using System.IO;
using System.Reflection;
namespace Debug01
{
class Program
{
private static string errorFile =
@"C:\SourceCode\EMPLOYEE\TEST\OUTPUT\EMPlog.txt";
static void Main(string[] args) {
string sourcefilePath =
@"C:\SourceCode\EMPLOYEE\TEST\INPUT\EMP01.xls";
string destinationFilePath =
@"C:\SourceCode\EMPLOYEE\TEST\OUTPUT\EMPFINAL.csv";
try
{
if (!File.Exists(sourcefilePath))
{
return;
}
if (File.Exists(errorFile))
{
File.Delete(errorFile);
}
writeLog("Converting xls to csv....");
convertExcelToCSV(sourcefilePath, "Sheet1", destinationFilePath);
writeLog("Parsing data ...");
var lines = File.ReadAllLines(destinationFilePath);
string[] info;
var list = new List<string>();
int rowNum = 1;
foreach (var line in lines)
{
if (!line.StartsWith("\"")) { continue; }
else if (line.Contains("ID #")) { continue; }
else if (line.Contains("Print Date:")) { continue; }
else
{
info = line.Split(',');
if (info.Length < 3) { continue; }
if ((info[0] == "\"\"") && (info[1] == "\"\"") && (info[2] == "\"\""))
{
continue;
}
else
{
if ((info[1] == "\"\"") && (info[2] == "\"\"") && (info[3] == "\"\"") && (info[4] == "\"\""))
{
var info2 = line.Split(new string[] { "\",\"" }, StringSplitOptions.None);
var data = rowNum++ + "," + info2[0] + "\",\"" + info2[5] + "\",\"" + info2[9].Replace("\"", "") + "\",\"" + info2[12] + "\"";
list.Add(data);
}
}
}
}
File.WriteAllLines(destinationFilePath, list.ToArray());
writeLog("Completed");
}
catch (Exception ex)
{
writeLog(ex.ToString());
} }
private static void writeLog(string message) {
File.AppendAllText(errorFile, DateTime.Now.ToString() + Environment.NewLine + message + Environment.NewLine); }
static void convertExcelToCSV(string sourceFile, string
worksheetName, string targetFile)
{
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sourceFile + ";Extended Properties=\"Excel 8.0;IMEX=1\"";
OleDbConnection conn = null;
StreamWriter wrtr = null;
OleDbCommand cmd = null;
OleDbDataAdapter da = null;
try
{
conn = new OleDbConnection(strConn);
conn.Open();
cmd = new OleDbCommand("SELECT * FROM [" + worksheetName + "$]", conn);
cmd.CommandType = CommandType.Text;
wrtr = new StreamWriter(targetFile);
da = new OleDbDataAdapter(cmd);
System.Data.DataTable dt = new System.Data.DataTable();
da.Fill(dt);
for (int x = 0; x < dt.Rows.Count; x++)
{
string rowString = "";
for (int y = 0; y < dt.Columns.Count; y++)
{
rowString += "\"" + dt.Rows[x][y].ToString() + "\",";
}
wrtr.WriteLine(rowString);
}
}
catch (Exception exc)
{
writeLog(exc.ToString());
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
conn.Dispose();
cmd.Dispose();
da.Dispose();
wrtr.Close();
wrtr.Dispose();
} }
} }