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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Taming Parameter Sniffing in SQL Server 2022 With PSP Optimization
  • PostgreSQL vs Oracle: When Higher Cost Means Better Performance
  • The English WHERE Clause: Plain-English Filters in Couchbase SQL++ Using Jev Model
  • Grounding AI Agents in Governed Data

Trending

  • GenAI Security Gateway: An End-to-End Architecture
  • Spring AI on Local LLMs
  • LangChainGo vs Genkit Go: Where Genkit Shines
  • One Database, Two Models: Building AI-Friendly Java Applications With MySQL JSON Duality Views

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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.

By 
Karthik Elumalai
·
Jul. 25, 16 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
15.1K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

  • Taming Parameter Sniffing in SQL Server 2022 With PSP Optimization
  • PostgreSQL vs Oracle: When Higher Cost Means Better Performance
  • The English WHERE Clause: Plain-English Filters in Couchbase SQL++ Using Jev Model
  • Grounding AI Agents in Governed Data

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook