Exporting Excel to C#

前端 未结 6 860
青春惊慌失措
青春惊慌失措 2020-12-21 16:44

I have to port excel file which business guys are using to calculate final price to C# so I can later use this algorithm in Asp.Net application. This is something I will be

6条回答
  •  不知归路
    2020-12-21 17:32

    Try to use this code, may it ll help

        public static void DataSetsToExcel(DataSet dataSet, string filepath)
        {
            try
            {
                string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties=Excel 12.0 Xml;";
                string tablename = "";
                DataTable dt = new DataTable();
                foreach (System.Data.DataTable dataTable in dataSet.Tables)
                {
                    dt = dataTable;
                    tablename = dataTable.TableName;
                    using (OleDbConnection con = new OleDbConnection(connString))
                    {
                        con.Open();
                        StringBuilder strSQL = new StringBuilder();
                        strSQL.Append("CREATE TABLE ").Append("[" + tablename + "]");
                        strSQL.Append("(");
                        for (int i = 0; i < dt.Columns.Count; i++)
                        {
                            strSQL.Append("[" + dt.Columns[i].ColumnName + "] text,");
                        }
                        strSQL = strSQL.Remove(strSQL.Length - 1, 1);
                        strSQL.Append(")");
    
                        OleDbCommand cmd = new OleDbCommand(strSQL.ToString(), con);
                        cmd.ExecuteNonQuery();
    
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            strSQL.Clear();
                            StringBuilder strfield = new StringBuilder();
                            StringBuilder strvalue = new StringBuilder();
                            for (int j = 0; j < dt.Columns.Count; j++)
                            {
                                strfield.Append("[" + dt.Columns[j].ColumnName + "]");
                                strvalue.Append("'" + dt.Rows[i][j].ToString().Replace("'", "''") + "'");
                                if (j != dt.Columns.Count - 1)
                                {
                                    strfield.Append(",");
                                    strvalue.Append(",");
                                }
                                else
                                {
                                }
                            }
                            if (strvalue.ToString().Contains("
    ")) { strvalue = strvalue.Replace("
    ", Environment.NewLine); } cmd.CommandText = strSQL.Append(" insert into [" + tablename + "]( ") .Append(strfield.ToString()) .Append(") values (").Append(strvalue).Append(")").ToString(); cmd.ExecuteNonQuery(); } con.Close(); } } } catch (Exception ex) { } }

提交回复
热议问题