关闭

C# 读取excel

156人阅读 评论(0) 收藏 举报
分类:
public  DataSet GetWorkbook(string filename)
        {
            DataSet ds = new DataSet();
            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();    //初始化Excel对象
            app.Visible = false;
            app.DisplayAlerts = false;
            object missing = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Excel.Workbook wb;
            try
            {
                wb = app.Workbooks.Open(filename, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                throw;
            }
            foreach (Microsoft.Office.Interop.Excel.Worksheet ws in wb.Sheets)
            {
                ds.Tables.Add(GetWorksheet(ws));
            }
            app.Workbooks.Close();
            app.Quit();
            return ds;
        }
        public  DataTable GetWorksheet(Microsoft.Office.Interop.Excel.Worksheet ws)
        {
            DataTable dt = new DataTable();
            dt.TableName = ws.Name;

            int row = ws.UsedRange.Rows.Count + 1;
            int col = ws.UsedRange.Columns.Count + 1;

            for (int c = 1; c < col; c++)
            {
                dt.Columns.Add("F" + c);
            }

            for (int r = 1; r < row; r++)
            {
                DataRow newRow = dt.NewRow();
                for (int c = 1; c < col; c++)
                {
                    newRow[c - 1] = ((Microsoft.Office.Interop.Excel.Range)ws.Cells[r, c]).Value2;  //问题是不是出在这里,请问怎么解决呢
                }
                dt.Rows.Add(newRow);
            }

            return dt;
        }


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:8725次
    • 积分:437
    • 等级:
    • 排名:千里之外
    • 原创:35篇
    • 转载:5篇
    • 译文:1篇
    • 评论:0条
    文章分类