DEV Community

IronSoftware
IronSoftware

Posted on • Originally published at ironsoftware.com

2 1

Save Excel to Database

Shows how to iterate data in an Excel WorkSheet and import that data into a System.Data.DataTable so that it may be saved to any SQL database supported by C#.

Entire WorkBooks can also be converted to System.Data.DataSet

C#:

using IronXL;
using System.Data;


WorkBook workbook = WorkBook.Load("test.xls");
WorkSheet sheet = workbook.DefaultWorkSheet;

//This is how you convert your worksheet to DataTable
//Boolean parameter allows you to set whether you want to treat your first row as column names of your table.
//The default value is false
var dataTable = sheet.ToDataTable(true);

//Optionally inspect your data
foreach (DataRow row in dataTable.Rows)
{
    for (int i = 0; i < dataTable.Columns.Count; i++)
    {
        Console.Write(row[i]);
    }
}



//Also you can convert the whole workbook to DataSet and work with it the way you like.
var dataSet = workbook.ToDataSet();

foreach (DataTable table in dataSet.Tables)
{
    Console.WriteLine(table.TableName);
}
Enter fullscreen mode Exit fullscreen mode

VB:

Imports IronXL
Imports System.Data


Private workbook As WorkBook = WorkBook.Load("test.xls")
Private sheet As WorkSheet = workbook.DefaultWorkSheet

'This is how you convert your worksheet to DataTable
'Boolean parameter allows you to set whether you want to treat your first row as column names of your table.
'The default value is false
Private dataTable = sheet.ToDataTable(True)

'Optionally inspect your data
For Each row As DataRow In dataTable.Rows
    For i As Integer = 0 To dataTable.Columns.Count - 1
        Console.Write(row(i))
    Next i
Next row



'Also you can convert the whole workbook to DataSet and work with it the way you like.
Dim dataSet = workbook.ToDataSet()

For Each table As DataTable In dataSet.Tables
    Console.WriteLine(table.TableName)
Next table
Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay