I want to iterate through rows in a table and read data from one column at the time. need to be able to separate data by the columns in the table so i can select ex. table 1 data from column 1, 2 and 4
my code
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
{
// Create an instance of the Open File Dialog Box
var openFileDialog1 = new OpenFileDialog();
// Set filter options and filter index
openFileDialog1.Filter = "Word Documents (.docx)|*.docx|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 1;
openFileDialog1.Multiselect = false;
// Call the ShowDialog method to show the dialog box.
openFileDialog1.ShowDialog();
textBox1.Text = openFileDialog1.FileName;
var word = new Microsoft.Office.Interop.Word.Application();
object miss = System.Reflection.Missing.Value;
object path = openFileDialog1.FileName;
object readOnly = true;
var docs = word.Documents.Open(ref path, ref miss, ref readOnly,
ref miss, ref miss, ref miss, ref miss,
ref miss, ref miss, ref miss, ref miss,
ref miss, ref miss, ref miss, ref miss,
ref miss);
dataGridView1.Columns.Add("explaineText", "col1");
dataGridView1.Columns.Add("CustomerText", "col2");
//dataGridView1.Columns.Add("CustomerText", "col5");
int ntab = 5;
Table t = docs.Tables[ntab];
Range r = t.Range;
int y = 1;
int i = 1;
Cells cells = r.Cells;
while (i <= cells.Count)
{
string txt = "";
string txt2 = "";
if (ntab != 5)
{
i = i + 2;
y = i + 1;
}
if(ntab == 5)
{
i = i + 6;
y = i + 4;
}
// Debug.WriteLine("iteration" + i + " i= " + i + "y= " + y);
try
{
Cell cell = cells[i];
Cell cell2 = cells[y];
Range r2 = cell.Range;
Range r3 = cell2.Range;
txt = r2.Text;
txt2 = r3.Text;
}
dataGridView1.Rows.Add(txt, txt2);
}
((_Document)docs).Close();
((_Application)word).Quit();
}
}
}
}
As you can see I try to read the row data by column by incrementing my counters according to which column I want to read.
I know there is a method cell.split but i haven't been able to implement it.
I'm sure there must be a better way to iterate through the rows and columns?
Note: I am only reading in the document, not editing.
I manage to find the anwser my self, in my experiment i just append the table data to a text file separating each column with "|" Here i can iterate each column in each row.
the code :
int ntab = 5;
Table t = docs.Tables[ntab];
Rows rows = t.Rows;
Columns cols = t.Columns;
for (int i = 1; i < rows.Count; i++) {
string ftxt = "";
for (int j = 1; j <= cols.Count; j++) {
Cell cell = rows[i].Cells[j];
Range r = cell.Range;
string txt = r.Text;
ftxt = ftxt + " | " + txt;
}
File.AppendAllText(@"c:\temp\test.txt", ftxt.ToString() + Environment.NewLine);
Console.WriteLine(ftxt);
}
Console.WriteLine("\n");
((_Document)docs).Close();
((_Application)word).Quit();
}