The clue to your problem is in the definition of the
Createtextfile
method
public static void Createtextfile(int lastUsedRow, int lastUsedColumn, Excel._Worksheet xlWorksheet)
You have a loop that starts from Column 1 and goes up to your columnsA value. If you only want to include a single column then pass the number of that column and just copy all the rows for it e.g.
public static void CreatetextfileFromColumn(int lastUsedRow, int ColumnToExport, Excel._Worksheet xlWorksheet)
{
string output = "";
string ExportPath = mypath;
for (int i = 1; i <= lastUsedRow; i++)
{
object xVal = ((Excel.Range)xlWorksheet.Cells[i, ColumnToExport]).Value;
if (xVal != null)
{
output += xVal.ToString();
}
output += Environment.NewLine;
}
FileStream fs = new FileStream(ExportPath, FileMode.Create, FileAccess.Write);
StreamWriter writer = new StreamWriter(fs);
writer.Write(output);
writer.Close();
}
EDIT after OP Comment
To call this function pass the number of the column you want to export as the
ColumnToExport
When you debug your code (always a good idea)
Excel.Range firstColumnA = (Excel.Range)xlWorksheetA.UsedRange.Columns[3];
int RowsA = firstColumnA.Rows.Count;
int ColumnsA = firstColumnA.Columns.Count;//clm numb
you will notice that the variable
RowsA
=
1.
That is because the variable
firstColumnA
contains a single column, the range "C:C".
So when you call my single-column function passing
RowsA
you are asking it to output Column 1 of the
Worksheet (
not the range firstColumnA)
When you call your original method with
RowsA
you are asking it to stop output after Column 1 of the
Worksheet (
not the range firstColumnA)
You might find this article usefule
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[
^]
Debugging code for absolute beginners - Visual Studio (Windows) | Microsoft Docs[
^]