PDA

View Full Version : سوال: وارد نكردن نام ستون Excel در صورت وجود به DataGridView



haamidd
چهارشنبه 07 آبان 1393, 09:29 صبح
من میخوام زمانیکه از اکسل اطلاعات وارد DataGridView میکنم دیگه سطون هایی رو که در وجود DataGridView داره رو دوباره نسازه!

كد من:


Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range range;

xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(Application.StartupPath + "\\output.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindow s, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1) ;

range = xlWorkSheet.UsedRange;

for (int columnCounter = 1; columnCounter <= range.Columns.Count; columnCounter++)
{
this.dataGridView1.Columns.Add(xlWorkSheet.Cells[1, columnCounter].Value2, xlWorkSheet.Cells[1, columnCounter].Value2);
}
//get the value of each excel cell and put into this variable
string str;
//Loop counters
int rowCounter = 0;
int columnCounter2 = 0;

for (rowCounter = 2; rowCounter <= range.Rows.Count; rowCounter++)
{
//Create a new row into the datagridview
this.dataGridView1.Rows.Add();
for (columnCounter2 = 1; columnCounter2 <= range.Columns.Count; columnCounter2++)
{
str = Convert.ToString((range.Cells[rowCounter, columnCounter2] as Excel.Range).Value2);
//add the value of excel file into the new row
this.dataGridView1.Rows[rowCounter - 2].Cells[columnCounter2 - 1].Value = str;
}
}
xlWorkBook.Close(true, null, null);
xlApp.Quit();

releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);


به نظرم باید یک if در اولین for که مربوط به ساختن سطون هاست بگذاریم!
امــــــا چطوری؟



ممنون میشم راهنمایی کنید