Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9046453
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T11:39:51+00:00 2026-06-16T11:39:51+00:00

I’m using the EPPlus .NET library in order to export data from SQL Server

  • 0

I’m using the EPPlus .NET library in order to export data from SQL Server to an Excel file.

I’m using the SqlConnection class to read the data. For every row of the SqlDataReader cursor, I iterate through all the excel cells for the corresponding row, and enter the data from the reader.

The issue is that I’m getting an “out of memory” error when im using this function for large tables. I need a method to create some kind of a buffer inside the Read CURSOR.

A concise code example:

Dim sqlConnection As SqlConnection = New SqlConnection()
sqlConnection.ConnectionString = sqlConnectionString.ConnectionString 'connectionstring built before

Dim query As SqlCommand = New SqlCommand(query...)

Dim newFileStream As New FileStream("c:\junk\test.xlsx", System.IO.FileMode.Create,System.IO.FileAccess.ReadWrite)

Using excelApp As New ExcelPackage(newFileStream)
    sqlConnection.Open()
    Dim sqlReader As SqlDataReader = query.ExecuteReader()

    Dim numOfColumns As Byte = sqlReader.FieldCount()
    Dim rowNumber As Integer = 1

    While sqlReader.Read()
        Dim currentColumn As Byte

        For currentColumn = 1 To numOfColumns
            ws.Cells(rowNumber,currentColumn).Value = sqlReader.Item(currentColumn - 1)
        Next
     rowNumber += 1             
    End While

    excelApp.Save()
End Using

newFileStream.Close()
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T11:39:53+00:00Added an answer on June 16, 2026 at 11:39 am

    Since you will have to split the files anyway when you hit Excel’s limits, here’s some code that reads from the database in chunks into multiple Excel files:

    static class Program
    {
        private static string _dataSource;
        private static string _database;
        private static string _table;
        private static string _outputPath;
        private static int _batchSize;
    
        public static void Main()
        {
            try
            {
               _dataSource = ConfigurationManager.AppSettings["DataSource"];
               _database = ConfigurationManager.AppSettings["Database"];
               _table = ConfigurationManager.AppSettings["Table"];
               _outputPath = ConfigurationManager.AppSettings["OutputPath"];
               _batchSize = int.Parse(ConfigurationManager.AppSettings["BatchSize"]);
    
                CreateExcel(_dataSource, _database, _table, _outputPath, "SELECT * FROM " + _table);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
    
            Console.WriteLine("All done!");
        }
    
        public static void CreateExcel(string dataSource, string databaseName, string tableName, string outputFilePath, string queryNoParameters)
        {
            var sqlConnectionString = new SqlConnectionStringBuilder
                {
                    DataSource = dataSource,
                    InitialCatalog = databaseName,
                    IntegratedSecurity = true
                };
    
            using (var connection = new SqlConnection(sqlConnectionString.ConnectionString))
            {
                connection.Open();
                using (var command = new SqlCommand { Connection = connection, CommandType = CommandType.Text, CommandText = queryNoParameters })
                using (var sqlReader = command.ExecuteReader())
                {
                    int i = 0;
                    while (WriteExcelFile(tableName, GetFileInfo(databaseName, tableName, outputFilePath, i++),
                                          sqlReader, sqlReader.FieldCount, _batchSize))
                    {
                        Console.WriteLine("Reading next batch...");
                    }
                }                
            }
        }
    
        private static bool WriteExcelFile(string tableName, FileInfo fileInfo, IDataReader sqlReader, int numOfColumns, int count)
        {
            using (var excelPackage = new ExcelPackage(fileInfo))
            {
                ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add(tableName);
    
                Console.WriteLine("Populating header row...");
                for (var currentColumn = 1; currentColumn <= numOfColumns; currentColumn++)
                {
                    worksheet.Cells[1, currentColumn].Value = sqlReader.GetName(currentColumn - 1);
                    worksheet.Column(currentColumn).Style.Numberformat.Format =
                        TranslateSystemtypeToExceltype(sqlReader.GetFieldType(currentColumn - 1));
                }
    
                Console.WriteLine("Reading data rows...");
                int rowNumber = 2;
                while (rowNumber <= count + 1 && sqlReader.Read())
                {
                    for (var currentColumn = 1; currentColumn <= numOfColumns; currentColumn++)
                        worksheet.Cells[rowNumber, currentColumn].Value = sqlReader[currentColumn - 1];
                    rowNumber++;
                }
    
                if (rowNumber == 2) //nothing read
                {
                    Console.WriteLine("Nothing to read, reached end of table!");
                    return false;
                }
    
                Console.WriteLine("Saving Excel file...");
                excelPackage.Save();
                return rowNumber == count + 2; //in which case we want to read more
            }
        }
    
        private static FileInfo GetFileInfo(string databaseName, string tableName, string outputFilePath, int i)
        {
            return new FileInfo(Path.Combine(outputFilePath,
                                          Path.ChangeExtension(
                                              string.Format("{0}_{1}_{2}", databaseName, tableName.Replace('.', '-'), i), "xlsx")));
        }
    
        public static string TranslateSystemtypeToExceltype(Type sysType)
        {
            if (sysType == typeof(string))
                return "@";
            if (sysType == typeof(DateTime))
                    return "dd/MM/YYYY";
            if (sysType == typeof(Decimal))
                    return "0.000";
            if (sysType == typeof(bool))
                    return "@";
            if (sysType == typeof(int))
                    return "0";
            if (sysType == typeof(short))
                    return "0";
            if (sysType == typeof(double))
                    return "0.000";
            return "General";
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to find ID3V2 tags from MP3 file using jid3lib in Java.
I am using jsonparser to parse data and images obtained from json response. When
We are using XSLT to translate a RIXML file to XML. Our RIXML contains
I'm using an ASP request returning a XML file containing some latin characters. By
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
I am using JSon response to parse title,date content and thumbnail images and place
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
That's pretty much it. I'm using Nokogiri to scrape a web page what has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.