DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modern Digital Website Security: Prepare to face any form of malicious web activity and enable your sites to optimally serve your customers.

Containers Trend Report: Explore the current state of containers, containerization strategies, and modernizing architecture.

Low-Code Development: Learn the concepts of low code, features + use cases for professional devs, and the low-code implementation process.

E-Commerce Development Essentials: Considering starting or working on an e-commerce business? Learn how to create a backend that scales.

Related

  • How To Convert MySQL Database to SQL Server
  • Making Spring AI and OpenAI GPT Useful With RAG on Your Own Documents
  • Accelerating Insights With Couchbase Columnar
  • Best Methods To Backup and Restore Database in SQL Server

Trending

  • Kubernetes Monitoring: Ensuring Performance and Stability in Containerized Environments
  • AI in Java: Building a ChatGPT Clone With Spring Boot and LangChain
  • How To Get Cell Data From an Excel Spreadsheet Using APIs in Java
  • Navigating Software Leadership in a Dynamic Era
  1. DZone
  2. Data Engineering
  3. Databases
  4. Import and Export Excel Files into Varbinary (Max) in SQL Server

Import and Export Excel Files into Varbinary (Max) in SQL Server

See how to combine a bit of C#, MS SQL, and ASPX to create quick and easy import and export buttons for your database.

Karthik Elumalai user avatar by
Karthik Elumalai
·
Jul. 25, 16 · Tutorial
Like (1)
Save
Tweet
Share
14.1K Views

Join the DZone community and get the full member experience.

Join For Free

introduction

in this article, you will learn how to import and export excel files into varbinary (max) in sql server using asp.net c#

what are the advantages of storing as a varbinary file?

  • we don't need to depend on the file system.
  • it will avoid data risks.

aspx code

just add two buttons:

<asp:button id="btnimportexceltodb" runat="server" text="importexceltodb" onclick="btnimportexceltodb_click" />  
<asp:button id="btnexportexcelfromdb" runat="server" text="exportexcelfromdb" onclick="btnexportexcelfromdb_click" />  


codebehind code

import code

//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();  
    }  
}  


export code

protected void btnexportexcelfromdb_click(object sender, eventargs e)  
{  
    string filepathtostore = @ "d:\tpms\uploaded_boq\raveena_boq_from_db.xlsx";  
    retrieveexcelfilefromdatabase(4, filepathtostore);  
}  
  
public void retrieveexcelfilefromdatabase(int id, string excelfilename)   
{  
    byte[] excelcontents;  
    string selectstmt = "select filecontent from dbo.tender_excel_source where file_sequence_no = @id";  
  
    using(sqlconnection connection = new sqlconnection(osmc.constring_property))  
    using(sqlcommand cmdselect = new sqlcommand(selectstmt, connection))   
    {  
        cmdselect.parameters.add("@id", sqldbtype.int).value = id;  
  
        connection.open();  
        excelcontents = (byte[]) cmdselect.executescalar();  
        connection.close();  
    }  
  
    file.writeallbytes(excelfilename, excelcontents);  
}  


database create table script

use [tpms_release1]  
go  
  
/****** object: table [dbo].[tender_excel_source] script date: 09-06-16 morning 10:19:05 ******/  
set ansi_nulls on  
go  
  
set quoted_identifier on  
go  
  
set ansi_padding on  
go  
  
create table [dbo].[tender_excel_source](  
    [fk_tender_id] [int] null,  
    [file_sequence_no] [int] identity(1,1) not null,  
    [filename] [nvarchar](1024) null,  
    [filecontent] [varbinary](max) null  
) on [primary] textimage_on [primary]  
  
go  
  
set ansi_padding off  
go  


output

when you're done, it should look like this:

output


click on the import button, and the excel file will have been converted to a byte file and will be saved like this:

excel file


click on the export button, and the opposite will happen:

excel file



excel file


i hope the above information was useful. kindly leave your feedback or suggestions.

sql

Published at DZone with permission of Karthik Elumalai. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How To Convert MySQL Database to SQL Server
  • Making Spring AI and OpenAI GPT Useful With RAG on Your Own Documents
  • Accelerating Insights With Couchbase Columnar
  • Best Methods To Backup and Restore Database in SQL Server

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: