Thursday, June 26, 2014

example C# and EXCEL just function ReadExcelFile

static void ReadExcelFile(string excelfilepath)
        {
            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Open(excelfilepath);

            int sheet_ii = 0;
            foreach (Worksheet sheet in wb.Sheets)
            {
                Console.WriteLine(string.Format("sheet{0}: {1}", sheet_ii, sheet.Name));
                int rows_count = sheet.UsedRange.Rows.Count;
                int cols_count = sheet.UsedRange.Columns.Count;
                Console.WriteLine(string.Format("rows={0} cols={1}", rows_count, cols_count));
                Range cellA1 = sheet.get_Range("A1");
                if (rows_count == 1 && cols_count == 1 && cellA1.get_Value() == null)
                {
                    Console.WriteLine("EMPTY SHEET");
                }
                else
                {
                    foreach (Microsoft.Office.Interop.Excel.Range row in sheet.UsedRange.Rows)
                    {
                        int rownum = row.Row;
                        foreach (Range cell in row.Cells)
                        {
                            if (cell.get_Value() == null)
                                Console.Write(string.Format("{0}=NULL ", cell.get_Address()));
                            else
                                Console.Write(string.Format("{0} ", cell.get_Value()));
                        }
                        Console.WriteLine();
                    }
                }

                sheet_ii++;
                Console.WriteLine();
                Console.WriteLine();
            }

            wb.Close();
            app.Quit();
        }//ReadExcelFile

No comments:

Post a Comment