-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathXlsxToCsv.cs
236 lines (205 loc) · 10.3 KB
/
XlsxToCsv.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml.Serialization;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
namespace Converter
{
/// <summary>
/// Converting Xlsx To Csv Class
/// </summary>
public class XlsxToCsv
{
/// <summary>
/// Alphabet to find columns
/// </summary>
private const string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
/// <summary>
/// Converting a XLSX File to a CSV File
/// </summary>
/// <param name="excelFilePath">Full xlsx file path</param>
public static bool Converter_XlsxToCsv(string excelFilePath)
{
var fileToWrite = System.IO.Path.Combine(Path.GetDirectoryName(excelFilePath), System.IO.Path.GetFileNameWithoutExtension(excelFilePath) + ".csv");
var outputFile = new StreamWriter(fileToWrite, false, Encoding.UTF8);
try
{
using (SpreadsheetDocument myDoc = SpreadsheetDocument.Open(excelFilePath, true))
{
WorkbookPart workbookPart = myDoc.WorkbookPart;
WorksheetPart worksheetPart = workbookPart.GetPartById("rId1") as WorksheetPart;
int dateIndex = -1;
int styleIndex = 0;
List<int> countDateForm = new List<int>();
foreach (CellFormat format in workbookPart.WorkbookStylesPart.Stylesheet.CellFormats)
{
//if (format.NumberFormatId == 14 )
//{
// dateIndex = styleIndex;
// break;
//}
if (format.NumberFormatId == 14)
countDateForm.Add(styleIndex);
++styleIndex;
}
var sharedDico = new Dictionary<string, string>();
int i = 0;
workbookPart.SharedStringTablePart.SharedStringTable.ChildElements.ToList().ForEach(e => sharedDico.Add(i++.ToString(), e.InnerText.Replace(";", ":").Replace("\n", "").Replace("'", " ")));
StringBuilder lineBuilder = null;
bool isSharedString = false;
char previousColumn = default(char);
bool mustAddValue = false;
string[] Col;
int nb_column = 0;
int column = 0;
bool firstDetec = false;
bool isDate = false;
bool isCellFormul = false;
OpenXmlReader reader = OpenXmlReader.Create(worksheetPart);
while (reader.Read())
{
if (reader.LocalName == "row")
{
if (reader.IsStartElement)
{
lineBuilder = new StringBuilder();
mustAddValue = false;
}
else
{
Col = lineBuilder.ToString().Split(';');
column = Col.Count();
if (firstDetec == false)
{
nb_column = column;
firstDetec = true;
}
if (nb_column == column && firstDetec == true)
outputFile.WriteLine(lineBuilder.ToString());
else if (nb_column > column && firstDetec == true)
{
int nbColMissing = nb_column - column;
string sep = null;
for (int ajoutCol = 0; ajoutCol < nbColMissing; ajoutCol++)
sep += ';';
outputFile.WriteLine(lineBuilder.ToString() + sep);
}
else if (nb_column < column && firstDetec == true)
{
int nbColMissing = column - nb_column;
int countLastChar = 0;
for (int ajoutCol = lineBuilder.Length - 1; ajoutCol >= 0; ajoutCol--)
{
if (lineBuilder[ajoutCol] != ';') break;
countLastChar++;
}
if (countLastChar == nbColMissing)
outputFile.WriteLine(lineBuilder.ToString().Substring(0, lineBuilder.Length - nbColMissing));
else
outputFile.WriteLine(lineBuilder.ToString());
}
else
outputFile.WriteLine(lineBuilder.ToString());
}
continue;
}
if (reader.IsEndElement)
continue;
if (reader.LocalName == "c")
{
if (mustAddValue)
lineBuilder.Append(";");
isSharedString = reader.Attributes.Any(a => a.LocalName == "t");
//isDate = reader.Attributes.Any(a => a.LocalName == "s" && a.Value == dateIndex.ToString());
isDate = reader.Attributes.Any(a => a.LocalName == "s" && countDateForm.Contains(Convert.ToInt32(a.Value)));
OpenXmlAttribute codeCellule = reader.Attributes.FirstOrDefault(a => a.LocalName == "r");
if (codeCellule != null)
{
char cellColumn = Regex.Replace(codeCellule.Value, "[0-9]", "").Last();
int indexCol = ALPHABET.IndexOf(cellColumn);
int indexPreviousCol = ALPHABET.IndexOf(previousColumn);
int diff = indexCol - indexPreviousCol;
if (diff > 1)
{
for (int j = 1; j < diff; j++)
lineBuilder.Append(";");
}
previousColumn = cellColumn;
}
mustAddValue = true;
continue;
}
if (reader.LocalName == "f")
isCellFormul = true;
if (reader.LocalName == "v")
{
string value = reader.GetText();
if (value.StartsWith("#"))
lineBuilder.Append(string.Empty);
else if (isSharedString && !isCellFormul)
lineBuilder.Append(sharedDico[value]);
else if (isSharedString && !isDate)
lineBuilder.Append(value);
else if (isDate && !value.Contains('-') && !value.Contains('+') && !value.Contains('.') && !value.Contains(','))
lineBuilder.Append(DateTime.FromOADate(double.Parse(value)).ToShortDateString());
else if (value.Contains("E-") || value.Contains("E+"))
lineBuilder.Append(decimal.Parse(value.ToString(), NumberStyles.Any, CultureInfo.InvariantCulture));
else
{
if (value.Contains('.') || value.Contains(','))
lineBuilder.Append(double.Parse(value, NumberStyles.Any, CultureInfo.InvariantCulture));
else
lineBuilder.Append(value);
}
lineBuilder.Append(";");
isCellFormul = false;
mustAddValue = false;
continue;
}
}
}
outputFile.Close();
return true;
}
catch (OleDbException)
{
return false;
}
}
public void SerializeDataSet(string filename, char separator)
{
string fileToWrite = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(filename), System.IO.Path.GetFileNameWithoutExtension(filename) + ".xml");
XmlSerializer ser = new XmlSerializer(typeof(DataSet));
DataSet ds = new DataSet("Fichier");
DataTable t = new DataTable("Colonne");
DataColumn c = new DataColumn("Valeur");
t.Columns.Add(c);
ds.Tables.Add(t);
DataRow r;
foreach (string line in File.ReadLines(filename, Encoding.Default))
{
string[] splitedLine = line.Split(separator);
foreach (string value in splitedLine)
{
r = t.NewRow();
r[0] = value;
t.Rows.Add(r);
}
}
using (TextWriter writer = File.CreateText(fileToWrite))
{
ser.Serialize(writer, ds);
writer.Close();
}
}
}
}