Thursday, January 6, 2011

Import Excel using OLEDB

You may need to impor a namespace:
using System.Data.OleDb;

//New DataTAble
table = new DataTable();

//Conection Straig For Excel Files
//FilePath is the direccion where the file is stored
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + FilePath + "; Jet OLEDB:Engine Type=5;" +
"Extended Properties=Excel 8.0;";

//Establish Coneccion
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
OleDbCommand comm = new OleDbCommand();
comm.CommandType = CommandType.Text;
comm.Connection = conn;

//Query for the Sheet
//Hoja is the name of the sheet
comm.CommandText = "SELECT * FROM ["+ Hoja +"$]";

//Execute Query and stores in a DataTable
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = comm;
adapter.Fill(table);
conn.Close();

//Then you can put the informacion in a grid
//MyGrid.DataSource = table
//Or take the table and insert into a databases

Export to Excel using StreamWriter Interop

You need to impor:
using excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
 
//Variables
excel.Application App;
excel.Workbook WB;
excel.Worksheet wsheet;
excel.Range range;

//Open New Instance of Excel
App = new excel.Application();
App.Visible = true;
App.DisplayAlerts = false;

//New Workbook
WB = App.Workbooks.Add(Missing.Value);

//New Sheet
wsheet = (excel.Worksheet)WB.ActiveSheet;
wsheet.Name = "Hoja";

//Procces DataTable
int Aux = 1;
foreach (DataRow row in table.Rows)
{
     Aux+=1;
     for (int i = 1; i < table.Columns.Count + 1; i++)
     {
          //Add Headers
          if (Aux == 2)
          {
               wsheet.Cells[1, i] = table.Columns[i - 1].ColumnName;
          }
          wsheet.Cells[Aux, i] = row[i - 1].ToString();
     }
}

Export to Excel using StreamWriter

I assume that you had filled a datagriview with a datatable and add namespace System.IO

// Set location to save the file, name and extension
SaveFileDialog SaveFile = new SaveFileDialog();
SaveFile.DefaultExt = "csv";
SaveFile.FileName = "HojaTest";
SaveFile.Filter = "csv";
 
if (SaveFile.ShowDialog() == DialogResult.OK)
{
SaveFile.AddExtension = true;
//Create File
StreamWriter sw = new StreamWriter(SaveFile.FileName, false);
string Headers = "";
 
//Write headers to the file
foreach (DataGridViewColumn col in grid.Columns)
{
    if (Headers != "")
         Headers += ",";
    Headers += col.Name;
}
sw.Write(Headers);
sw.Write(sw.NewLine); 
 
//Write the informacion to excel file
foreach (DataRow row in table.Rows)
{
     for (int i = 0; i < table.Columns.Count ; i++)
     {
           if (!row[i].Equals(DBNull.Value))
                sw.Write(row[i].ToString().Replace(",", "."));
           if (i < table.Columns.Count - 1)
                 sw.Write(",");
      }
sw.Write(sw.NewLine);
}
sw.Close();
MessageBox.Show("Datos Exportados");