天天看点

.net中使用微软类库 导出excel(源代码)

/// <summary>

        ///

        /// </summary>

        /// <param name="ds">要导出的DataTable(包含列头)</param>

        /// <param name="strPath">Excel保存地址</param>

        public static void ExportExcelMethod(System.Data.DataTable ds, string strPath)

        {

            if (ds != null && !ds.Equals(""))

            {

                return;

            }

            Excel.ApplicationClass _x = new ApplicationClass();

            Excel.WorkbookClass wb = (Excel.WorkbookClass)_x.Workbooks.Add(System.Reflection.Missing.Value);

            System.Data.DataTable dt = ds;

            for (int i = 0; i < dt.Columns.Count; i++)

            {

                _x.Cells[1, i + 1] = dt.Columns[i].ColumnName;

            }

            for (int i = 0; i < dt.Rows.Count; i++)

            {

                for (int j = 0; j < dt.Columns.Count; j++)

                {

                    _x.Cells[2 + i, j + 1] = dt.Rows[i][j].ToString();

                }

            }

            wb.Saved = true;

            _x.ActiveWorkbook.SaveCopyAs(strPath);

        }