So i have this excel with around 2200 rows that i need to read and write to a txt file, the problem is that it takes way too much time, I've been told that reading/writing files it usually takes time because it's nature, so i tried read only once the excel file, use a stringBuilder and write per line (haven't tried storing all the text and writing to whole .txt file)
But, is there any way i can speed this up?
Selecting smaller ranges, like only 1 row? Builing a gigantic string with \n as line-breaks and then write all that to the .txt?
Here's a sample of my code
using Excel = Microsoft.Office.Interop.Excel;
[...]
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open("C:/Users/MyUser/Desktop/SomeFolder/my_excel.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Excel.Range allRange = xlWorkSheet.UsedRange;
try
{
System.IO.StreamWriter file = new System.IO.StreamWriter("C:\\test.txt");
String line = "";
//StringBuilder line;
for (int row = 1; row <= allRange.Rows.Count; row++) //These are up to thousand sometimes
{
if (allRange.Value2[row, 1] != "")
{
//line = new StringBuilder();
for (int column = 1; column <= 6; column++)
{
//Console.WriteLine(allRange.Value2[row, column]);
line += allRange.Value2[row, column];
if (column != 6)
{
line += "|";
//line.Append("|");
}
}
file.WriteLine(line);
line = "";
}
else
{
MessageBox.Show("Should've not reached here.");
break;
}
}
file.Close();
}
catch (Exception ex)
{
MessageBox.Show("Couldn't write file: " + ex.ToString());
}
Btw I'm using .NET v4.0.30319... i think (Says on Environment.Version.ToString())
Or .NET v4.5.51209 (Says on "Help" > "About Microsoft Visual Studio")
Excel.Range allRange = xlWorkSheet.UsedRange;([A,1],[AD,2210]) and reading the value cell by cell, takes much more times than selecting a smaller range (i only need the first 6 columns). While writing to file takes a bit less than 1 sec. So now i can try the solution @sławomir-rosiek sugested, using OpenXML SDK