SoFunction
Updated on 2025-03-01

C# operation EXCEL DataTable conversion example code


//Load Excel
        public   DataSet LoadDataFromExcel(string filePath)
        {
            try
            {
                string strConn;
                //strConn = "Provider=.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'";
                strConn = ("Provider=.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'", filePath);
                OleDbConnection OleConn = new OleDbConnection(strConn);
                ();
String sql = "SELECT * FROM  [Sheet1$]";//But change the Sheet name, such as sheet2, etc.

                OleDbDataAdapter OleDaExcel = new OleDbDataAdapter(sql, OleConn);
                DataSet OleDsExcle = new DataSet();
                (OleDsExcle, "Sheet1");
                ();
                return OleDsExcle;
            }
            catch (Exception err)
            {

                return null;
            }
        }

        /// <summary>
/// DataTable directly exports Excel. This method will open the DataTable data in Excel and then manually save it to the exact location.
        /// </summary>
/// <param name="dt">To export Excel's DataTable</param>
        /// <returns></returns>
        public bool DoExport( dt)
        {
            app = new ApplicationClass();
            if (app == null)
            {
throw new Exception("Excel cannot start");
            }
            = true;
            Workbooks wbs = ;
            Workbook wb = ();
            Worksheet ws = (Worksheet)[1];

            int cnt = ;
            int columncnt = ;

// ********************* Get data*********************
object[,] objData = new Object[cnt + 1, columncnt];  // Create cached data
// Get column title
            for (int i = 0; i < columncnt; i++)
            {
                objData[0, i] = [i].ColumnName;
            }
// Get specific data
            for (int i = 0; i < cnt; i++)
            {
                dr = [i];
                for (int j = 0; j < columncnt; j++)
                {
                    objData[i + 1, j] = dr[j];
                }
            }

//*************************** Write to Excel*********************
            Range r = ws.get_Range([1, 1], [cnt + 1, columncnt]);
            = "@";
            //r = r.get_Resize(cnt+1, columncnt);
            r.Value2 = objData;
            ();

            app = null;
            return true;
        }