c# - 我想在保存格式更改时从 Excel 上传数据并存储在 SQL Server 中
问题描述
我从 Excel 导入数据并保存到临时表中,之后它将保存在主表中,临时表将truncate.all
正确保存数据,仅以日期格式出现问题,因为在 Excel 中它是DD/MM/YYYY
但在保存时保存MM/DD/YYYY
在 SQL 中服务器。
如何在 SQL Server 中节省MM/DD/YYYY
时间?DD/MM/YYYY
我尝试了许多解决方案,但没有得到任何积极的结果。甚至尝试在查询中进行转换,但也反映了相同的结果。
protected void Upload(object sender, EventArgs e)
{
try
{
string FilePath = Convert.ToString(Session["FilePath"]);
string conString = string.Empty;
string Filename = Session["Filename"].ToString();
//string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
string extension = Filename.Substring(Filename.LastIndexOf('.'));
switch (extension)
{
case ".xls": //Excel 97-03
conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx": //Excel 07 or higher
conString = ConfigurationManager.ConnectionStrings["Excel07+ConString"].ConnectionString;
break;
}
conString = string.Format(conString, FilePath);
using (OleDbConnection excel_con = new OleDbConnection(conString))
{
excel_con.Open();
//string sheet1 = "Index Of Charge";
//string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[1]["TABLE_NAME"].ToString();
DataTable dtExcelData = new DataTable();
//[OPTIONAL]: It is recommended as otherwise the data will be considered as String by default.
dtExcelData.Columns.AddRange(new DataColumn[9] {
new DataColumn("SNo", typeof(int)),
new DataColumn("SRN", typeof(string)),
new DataColumn("Charge Id",typeof(string)),
new DataColumn("Charge Holder Name",typeof(string)),
new DataColumn("Date of Creation",typeof(string)),
new DataColumn("Date of Modification",typeof(string)),
new DataColumn("Date of Satisfaction",typeof(string)),
new DataColumn("Amount",typeof(decimal)),
new DataColumn("Address",typeof(string))});
//new DataColumn("CreatedDate",typeof(string)),
//new DataColumn("ModifiedDate",typeof(string)),
//new DataColumn("CreatedBy",typeof(int))});
string sheet1 = DdlSheetNames.SelectedItem.Text;
using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + sheet1 + "]", excel_con))
{
oda.Fill(dtExcelData);
}
excel_con.Close();
string consString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(consString))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
{
//Set the database table name
sqlBulkCopy.DestinationTableName = "dbo.INDEXOFCHARGE";
//[OPTIONAL]: Map the Excel columns with that of the database table
sqlBulkCopy.ColumnMappings.Add("SNo", "SNo");
sqlBulkCopy.ColumnMappings.Add("SRN", "SRN");
sqlBulkCopy.ColumnMappings.Add("Charge Id", "ChargeId");
sqlBulkCopy.ColumnMappings.Add("Charge Holder Name", "ChargeHolderName");
sqlBulkCopy.ColumnMappings.Add("Date of Creation", "DateofCreation");
sqlBulkCopy.ColumnMappings.Add("Date of Modification", "DateofModification");
sqlBulkCopy.ColumnMappings.Add("Date of Satisfaction", "DateofSatisfaction");
sqlBulkCopy.ColumnMappings.Add("Amount", "Amount");
sqlBulkCopy.ColumnMappings.Add("Address", "Address");
con.Open();
sqlBulkCopy.WriteToServer(dtExcelData);
con.Close();
}
}
}
//update Fields
Myconn.Open();
SqlCommand cmd = new SqlCommand("dbo.SP_InsetCreatedby", Myconn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
SqlCommand cmd1 = new SqlCommand("dbo.UpdateDateFormat", Myconn);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.ExecuteNonQuery();
Myconn.Close();
//update complete
//show Details
ShowDetails_Click(sender, e);
//show details complete
}
catch (Exception ex)
{
string script = "<script>alert('" + ex.Message + "');</script>";
}
finally
{
}
//show Details complete
}
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.FileName != "")
{
string FolderName = "BasicDetails";
string Filename = FileUpload1.FileName;
Session["Filename"] = FileUpload1.FileName;
string RightNm = Filename.Substring(Filename.LastIndexOf('.') + 1);
int FileLen = RightNm.Length;
string LeftNm = Filename.Substring(0, Convert.ToInt32(Filename.Length) - (FileLen + 1)).ToString();
Filename = LeftNm + "-" + DateTime.Now.ToString("ddmmyyyy") + "." + RightNm;
bool folderExists = Directory.Exists(Server.MapPath(FolderName));
if (!folderExists)
Directory.CreateDirectory(Server.MapPath(FolderName));
string path = Server.MapPath(FolderName) + "\\" + Filename;
Session["FilePath"] = path;
FileUpload1.PostedFile.SaveAs(path);
string conString = string.Empty;
OleDbConnection excelConnection;
string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
switch (extension)
{
case ".xls": //Excel 97-03
conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx": //Excel 07 or higher
conString = ConfigurationManager.ConnectionStrings["Excel07+ConString"].ConnectionString;
break;
}
conString = string.Format(conString, path);
excelConnection = new OleDbConnection(conString);
excelConnection.Open();
DataTable Sheets = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
int rowcnt = 0;
DdlSheetNames.Items.Add("-Select-");
foreach (DataRow dr in Sheets.Rows)
{
string sht = dr[2].ToString().Replace("'", "");
OleDbDataAdapter dataAdapter = new OleDbDataAdapter("select * from [" + sht + "]", excelConnection);
rowcnt = rowcnt + 1;
DdlSheetNames.Items.Add(sht);
}
excelConnection.Close();
//
}
}
解决方案
您知道,日期格式在 SQL Server 中并不重要。只需确保您传递日期的字段是数据类型 DATE。请记住,数据的格式是数据的外观,但底层数据本身不会改变。如果你想改变格式,你可以这样做。
SELECT CONVERT(VARCHAR(10), GETDATE(), 101) AS [MM/DD/YYYY]
另外,考虑一下。
UPDATE [dbo].[MyTable]
SET [ToDateTime] = [ContainedData]
最后,您应该为下面的链接添加书签。
推荐阅读
- javascript - 在零处停止计时器
- c++ - 如何在 C++ 中制作通用 stringToVector 函数?
- webpack - 为什么我的更改没有显示在浏览器中?带有和不带有 webpack-dev-server 的 Webpack 和 HMR。第一个 webpack 配置
- python-3.x - 使用 destroy() 后无法关闭 tkinter
- python-3.x - 如何使用 Tensorflow 计算每个样本的梯度并使用任意函数减少它们?
- c# - 网络流错误“在写入所有字节之前无法关闭流”
- ruby-on-rails - 带有登录信息的公寓电梯
- floating-point - 如何从生成的代码中自动消除双精度数学?
- mongoose - Mongoose 聚合器问题(错误:参数必须是聚合管道运算符)
- r - 根据条件整理一个数据框中的行