How to write some data to excel file(.xlsx)

Matheus Mello
Matheus Mello
September 2, 2023
Cover Image for How to write some data to excel file(.xlsx)

How to Write Data to Excel File (.xlsx) Like a Pro 💪

So, you have a task at hand - writing data to an Excel file (.xlsx) in a specific format. 📝 But don't worry, my friend! I've got you covered. In this guide, I'll walk you through the process step by step, addressing common issues and providing easy solutions. Let's dive in and excel at it! 🚀

Step 1: Creating the Excel File

To create an Excel file in C#, you'll need to use a library that supports it. One popular option is the EPPlus library, which makes working with Excel files a breeze. 💨

First, make sure you have installed the EPPlus NuGet package in your project. Then, let's write some code to create our Excel file:

using OfficeOpenXml;

// Create a new Excel package
using var package = new ExcelPackage();

// Add a worksheet to the package
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet1");

// Save the Excel package to a file
string filePath = "c://test/files/work1_4.13.14.xlsx";
package.SaveAs(new FileInfo(filePath));

Voila! 🎉 You have successfully created an Excel file named work1_4.13.14.xlsx at the specified file path.

Step 2: Adding Headers

Now that we have our Excel file ready, let's add some headers to make it look more organized and professional. In your case, the headers are [Name], [Age], and [City].

worksheet.Cells["A1"].Value = "Name";
worksheet.Cells["B1"].Value = "Age";
worksheet.Cells["C1"].Value = "City";

In this example, we are assigning each header to a specific cell (A1, B1, C1). Feel free to customize the headers and their cell positions according to your needs.

Step 3: Writing Data

Now comes the fun part - filling the Excel sheet with your data! You mentioned having three List<string> objects containing names, ages, and cities. Let's assume you have them as nameList, ageList, and cityList respectively.

List<string> nameList = new List<string> { "Ben", "Jack", "Mike" };
List<string> ageList = new List<string> { "20", "25", "45" };
List<string> cityList = new List<string> { "xyz", "xyz", "zyx" };

// Write data to Excel sheet starting from cell A2
for (int i = 0; i < nameList.Count; i++)
{
    int row = i + 2; // We add 2 to start writing from the second row (A2)
    worksheet.Cells[row, 1].Value = nameList[i];
    worksheet.Cells[row, 2].Value = ageList[i];
    worksheet.Cells[row, 3].Value = cityList[i];
}

With this code snippet, we loop through each item in the lists and assign them to their respective cells in the Excel sheet, starting from the second row (A2).

Step 4: Saving the Changes

Lastly, we'll save the changes made to the Excel file.

package.Save();

And that's it! 🎊 You have successfully written data to an Excel file in the desired format. Give yourself a pat on the back, my friend! 🙌

Take It to the Next Level

Now that you have the basics, why not explore further? You can enhance your code by adding error handling, formatting options, or even create more advanced Excel templates using EPPlus. The possibilities are endless! 🌟

But hey, don't stop there! Share your achievements and let others learn from your experience. Use the hashtag #ExcelWizard on social media and join the community of Excel enthusiasts. Together, we can excel beyond limits! 💫

So, what are you waiting for? Start writing data to Excel files like a pro! 💻💼

Have any questions or need additional assistance? Leave a comment below and let's excel together! 👇

Take Your Tech Career to the Next Level

Our application tracking tool helps you manage your job search effectively. Stay organized, track your progress, and land your dream tech job faster.

Your Product
Product promotion

Share this article

More Articles You Might Like

Latest Articles

Cover Image for How can I echo a newline in a batch file?
batch-filenewlinewindows

How can I echo a newline in a batch file?

Published on March 20, 2060

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Cover Image for How do I run Redis on Windows?
rediswindows

How do I run Redis on Windows?

Published on March 19, 2060

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Cover Image for Best way to strip punctuation from a string
punctuationpythonstring

Best way to strip punctuation from a string

Published on November 1, 2057

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Cover Image for Purge or recreate a Ruby on Rails database
rakeruby-on-railsruby-on-rails-3

Purge or recreate a Ruby on Rails database

Published on November 27, 2032

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my