Adrija Adrija - 3 months ago 20
C# Question

Extracting an entire row from an excel file using C#

I am trying extract a complete row from an excel sheet one at a time.
For example suppose my excel is

**column name** A B C
**row value** Something1 Something2 Something3
**row value** S1 S2 S3


It will generate

<"Something1">,<"Something2">,<"Something3">
<"S1">,<"S2">,<"S3">


Till now the code I have used is:

for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
//new line
if (j == 1)
{
Console.WriteLine("\r\n");
}

//write the value to the console
if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null)
{
string cellValue = xlWorksheet.Cells[i,j].Value.ToString();
Console.WriteLine(cellValue);
string s = (cellValue);
Console.Write(xlRange.Cells[i, j].Value2.ToString() + "\t" +s);
}
}
}


Can someone please help?

Thanks in advance.

Answer

When range is copied in Excel, it is also put in the Clipboard as Tab separated values

xlWorksheet.UsedRange.Copy();
var TSV = System.Windows.Forms.Clipboard.GetText(); // add reference to System.Windows.Forms
var s = "<\"" + TSV.Trim().Replace("\t", "\">,<\"").Replace("\r\n", "\">\r\n<\"") + "\">";