Introduction
In this article you will get the detail about How to Import and Export Excel files into varbinary(max)in Sql server Using Asp.net C#
What are advantages of storing as varbinary file?
- We need not to depend on the file system,
- It will avoid the legal issues and data risk
Aspx code
Add just two buttons,
- <asp:Button ID="BtnImportExcelToDB" runat="server" Text="ImportExcelToDb" OnClick="BtnImportExcelToDB_Click" />
- <asp:Button ID="BtnExportExcelFromDB" runat="server" Text="ExportExcelFromDb" OnClick="BtnExportExcelFromDB_Click" />
Code for Import Excel to Db,
- //Button Click event for the ImportExcelToDB
- protected void BtnImportExcelToDB_Click(object sender, EventArgs e)
- {
- //Specify the filepath where the file exist
- string filename = @ "D:\TPMS\Uploaded_Boq\Raveena_Boq1.xlsx";
- //pass the filename as a parameter
- this.StoreExcelFileToDatabase(filename);
- }
- // store Excel sheet (or any file for that matter) into a SQL Server table
- public void StoreExcelFileToDatabase(string excelFileName)
- {
- // if file doesn't exist --> terminate (you might want to show a message box or something)
- if (!File.Exists(excelFileName))
- {
- return;
- }
- // get all the bytes of the file into memory
- byte[] excelContents = File.ReadAllBytes(excelFileName);
- // define SQL statement to use
- string insertStmt = "INSERT INTO dbo.Tender_Excel_Source(FileName, FileContent) VALUES(@FileName, @BinaryContent)";
- // set up connection and command to do INSERT
- using(SqlConnection connection = new SqlConnection(OSMC.constring_Property))
- using(SqlCommand cmdInsert = new SqlCommand(insertStmt, connection))
- {
- cmdInsert.Parameters.Add("@FileName", SqlDbType.VarChar, 500).Value = excelFileName;
- cmdInsert.Parameters.Add("@BinaryContent", SqlDbType.VarBinary, int.MaxValue).Value = excelContents;
- // open connection, execute SQL statement, close connection again
- connection.Open();
- cmdInsert.ExecuteNonQuery();
- connection.Close();
- }
- }





JosephsPosted May 13, 2023, 3:29 PM
Can you share excel file
Karthik ElumalaiPosted Jun 15, 2016, 1:59 AM
Thanks a lot Humayun Kabir Mamun
Humayun Kabir MamunPosted Jun 15, 2016, 1:20 AM
Nice...
Karthik ElumalaiPosted Jun 10, 2016, 12:32 PM
Thank you very much...: Rakesh
RakeshPosted Jun 10, 2016, 12:05 PM
Good one