I have a SSIS package which is pulling data from a SQL database and generating a comma delimited flat file. The flat file is to be used to import the data into a system and it is causing issues with the text field values in the file as it contains comma in the value.
I am now told to insert the pipe character | as the text qualifier for all text fields.
Example
1234,Smith, John,5678 should be 1234,|Smith, John|,5678
I followed the tutorial in this link to create my SSIS package for the export. It is using a Script Task with the Visual C# script pasted below, which I finding it difficult on how to modify to prepend and append the pipe character to the text values consisting the comma character.
I think it is this part where I will need to insert the pipe character, but I do not know the C# language enough to modify it as needed. Any help or reference resource would be really helpful and appreciated.
StreamWriter sw = null;
sw = new StreamWriter(FileFullPath, false);
// Write the Header Row to File
int ColumnCount = d_table.Columns.Count;
for (int ic = 0; ic < ColumnCount; ic++)
{
sw.Write(d_table.Columns[ic]);
if (ic < ColumnCount - 1)
{
sw.Write(FileDelimiter);
}
}
sw.Write(sw.NewLine);
// Write All Rows to the File
foreach (DataRow dr in d_table.Rows)
{
for (int ir = 0; ir < ColumnCount; ir++)
{
if (!Convert.IsDBNull(dr[ir]))
{
sw.Write(dr[ir].ToString());
}
if (ir < ColumnCount - 1)
{
sw.Write(FileDelimiter);
}
}
sw.Write(sw.NewLine);
}
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
try
{
//Declare Variables
string DestinationFolder = Dts.Variables["User::DestinationFolder"].Value.ToString();
string FileDelimiter = Dts.Variables["User::FileDelimiter"].Value.ToString();
string FileExtension = Dts.Variables["User::FileExtension"].Value.ToString();
//USE ADO.NET Connection from SSIS Package to get data from table
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(Dts.Connections["DBConn"].AcquireConnection(Dts.Transaction) as SqlConnection);
//Read list of Tables with Schema from Database
string query = "SELECT Schema_name(schema_id) AS SchemaName,name AS TableName FROM sys.tables WHERE is_ms_shipped = 0";
//MessageBox.Show(query.ToString());
SqlCommand cmd = new SqlCommand(query, myADONETConnection);
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
//Loop through datatable(dt) that has schema and table names
foreach (DataRow dt_row in dt.Rows)
{
string SchemaName = "";
string TableName = "";
object[] array = dt_row.ItemArray;
SchemaName = array[0].ToString();
TableName = array[1].ToString();
string FileFullPath =DestinationFolder +"\\"+ SchemaName+"_"+TableName + "_" + datetime+FileExtension;
//Get the data for a table into data table
string data_query = "Select * From ["+SchemaName+"].["+TableName+"]";
SqlCommand data_cmd = new SqlCommand(data_query, myADONETConnection);
DataTable d_table = new DataTable();
d_table.Load(data_cmd.ExecuteReader());
StreamWriter sw = null;
sw = new StreamWriter(FileFullPath, false);
// Write the Header Row to File
int ColumnCount = d_table.Columns.Count;
for (int ic = 0; ic < ColumnCount; ic++)
{
sw.Write(d_table.Columns[ic]);
if (ic < ColumnCount - 1)
{
sw.Write(FileDelimiter);
}
}
sw.Write(sw.NewLine);
// Write All Rows to the File
foreach (DataRow dr in d_table.Rows)
{
for (int ir = 0; ir < ColumnCount; ir++)
{
if (!Convert.IsDBNull(dr[ir]))
{
sw.Write(dr[ir].ToString());
}
if (ir < ColumnCount - 1)
{
sw.Write(FileDelimiter);
}
}
sw.Write(sw.NewLine);
}
sw.Close();
Dts.TaskResult = (int)ScriptResults.Success;
}
}
catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(Dts.Variables["User::LogFolder"].Value.ToString() + "\\" +
"ErrorLog_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
Is the package somewhat hard-code query written for getting data and what will be made available for the export process? If so, is the data ONLY for export process from the query? Or is it query data, show some report, then allow the export to comma separated list from same results?
I know, bunch of questions. But if your query is exclusively to pull the data for export, why not tack on the pipes as you query the data, something like
select
SomeIntegerColumn,
'|' + SomeStringField + '|' as SomeStringField,
'|' + AnotherString + '|' as AnotherString
SomeDateColumn,
etc
from
...
Then the data is already formatted for you ready to go.
Related
i have the following c# script on ssis project in visual studio that generates files based on a column value of a sql table and i would like to add a part that also splits the files when the record count reaches 200..Example of an extraction would be nameoffile_columnvalue_datetime_1.txt for the first 200,nameoffile_columnvalue_datetime_2.txt for the next 200 etc... thank you in advance!
public void Main()
{
// TODO: Add your code here
string datetime_1 = DateTime.Now.ToString("dd/MM/yyyy");
string datetime = datetime_1.Replace("/", String.Empty);
try
{
//Declare Variables
string FileNamePart = Dts.Variables["User::FlatFileNamePart"].Value.ToString();
string DestinationFolder = Dts.Variables["User::DestinationFolder"].Value.ToString();
string TableName = Dts.Variables["User::TableName"].Value.ToString();
string FileDelimiter = Dts.Variables["User::FileDelimiter"].Value.ToString();
string FileExtension = Dts.Variables["User::FileExtension"].Value.ToString();
string ColumnNameForGrouping = Dts.Variables["User::ColumnNameForGrouping"].Value.ToString();
string SubFolder = Dts.Variables["User::SubFolder"].Value.ToString();
Int32 RecordCntPerFile = (Int32)Dts.Variables["User::RecordsPerFile"].Value;
string RecordCntPerFileDecimal = RecordCntPerFile + ".0";
//USE ADO.NET Connection from SSIS Package to get data from table
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(Dts.Connections["AR_GSLO_OLTP"].AcquireConnection(Dts.Transaction) as SqlConnection);
//Read distinct Group Values for each flat file
string query = "Select distinct " + ColumnNameForGrouping + " from " + TableName;
//MessageBox.Show(query.ToString());
SqlCommand cmd = new SqlCommand(query, myADONETConnection);
//myADONETConnection.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
myADONETConnection.Close();
//Loop through values for ColumnNameForGroup
foreach (DataRow dt_row in dt.Rows)
{
string ColumnValue = "";
object[] array = dt_row.ItemArray;
ColumnValue = array[0].ToString();
//Load Data into DataTable from SQL ServerTable
string queryString =
"SELECT * from " + TableName + " Where " + ColumnNameForGrouping + "='" + ColumnValue + "'";
SqlDataAdapter adapter = new SqlDataAdapter(queryString, myADONETConnection);
DataSet ds = new DataSet();
adapter.Fill(ds);
foreach (DataTable d_table in ds.Tables)
{
string FileFullPath = SubFolder + "\\" + FileNamePart + "_" + ColumnValue + "_" + datetime + FileExtension;
StreamWriter sw = null;
sw = new StreamWriter(FileFullPath, false);
// Write the Header Row to File an thelw na exei kai header ta kanw uncomment apo 152 mexri 160 grammi
int ColumnCount = d_table.Columns.Count;
// for (int ic = 0; ic < ColumnCount; ic++)
//{
// sw.Write(d_table.Columns[ic]);
// if (ic < ColumnCount - 1)
// {
// sw.Write(FileDelimiter);
// }
//}
// sw.Write(sw.NewLine);
// Write All Rows to the File
foreach (DataRow dr in d_table.Rows)
{
for (int ir = 0; ir < ColumnCount; ir++)
{
if (!Convert.IsDBNull(dr[ir]))
{
sw.Write(dr[ir].ToString());
}
if (ir < ColumnCount - 1)
{
sw.Write(FileDelimiter);
}
}
sw.Write(sw.NewLine);
}
sw.Close();
}
}
}
catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(Dts.Variables["User::LogFolder"].Value.ToString() + "\\" +
"ErrorLog_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
}
So assuming/understanding you have a script task which is the source of your rows?
You can add a Rowcount Task to capture the amount of rows in a variable for later validation.
after that, you might need a new script task where you can do the validation of how many records there is. something like a case statement/if statement or a type of loop for each 200.. odd records to change a value/filename.
Using that loop, you can change the filename/filenamevariable.
So you would need your ConnectionManager File Destination to have an expression with this variable filename.
Thus as soon as it hits 200.. records, the script should change the filename and the output should create a new file.
I am not sure if it will like the in flight name change. but think this might be a way to point your thoughts.
i did it first i used a foreach loop container to take the name of the txts as input variables
then inside the loop i created a script with the following c# code
public void Main()
{
// TODO: Add your code here
string datetime_1 = DateTime.Now.ToString("dd/MM/yyyy");
string datetime = datetime_1.Replace("/", String.Empty);
StreamWriter writer = null;
try
{
//Declare Variables
string filename= Dts.Variables["User::FileName"].Value.ToString();
//MessageBox.Show(filename);
using (StreamReader inputfile = new System.IO.StreamReader(filename))
{
int count = 0;
int filecount = 0;
string line;
while ((line = inputfile.ReadLine()) != null)
{
if (writer == null || count > 199)
{
count = 0;
if (writer != null)
{
writer.Close();
writer = null;
}
++filecount;
writer = new System.IO.StreamWriter(filename.Replace(".txt", "_") + filecount.ToString() + ".txt", true);
}
writer.WriteLine(line);
++count;
}
}
}
catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(Dts.Variables["User::LogFolder"].Value.ToString() + "\\" +
"ErrorLog_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
finally
{
if (writer != null)
writer.Close();
}
Dts.TaskResult = (int)ScriptResults.Success;
}
and that was it!
I have a stored procedure that has multiple select statements using temp tables. I want to copy the results into one CSV file. Each result has different columns. I would like to copy them in such a way that each result set should leave two lines of space in CSV file.
Example below :
Sample stored procedure
Create procedure usp_Test_CSV_Report
As
Begin
select 'Text Sample' as Description, 123 Amount, 20210511 as Joindate
select GETDATE() as MonthATB
select 1 as AccountId, 'CI' as Name
select 'Sample Report'
End
The temp tables have been created within the stored procedure which will be called like Select * from #temp. I have not included real stored procedure which is vast.
I will be running the stored procedure using C#
string query = "EXEC alpha.dbo.usp_Test_CSV_Report";
SqlCommand cmd = new SqlCommand(query, SQLConnection);
SQLConnection.Open();
DataTable d_table = new DataTable();
SqlDataReader sqlReader = cmd.ExecuteReader();
while (sqlReader.Read())
{
d_table.Load(sqlReader);
// Write the Header Row to File
int ColumnCount = d_table.Columns.Count;
for (int ic = 0; ic < ColumnCount; ic++)
{
//MessageBox.Show(d_table.Columns[ic].ToString());
sw.Write(d_table.Columns[ic]);
if (ic < ColumnCount - 1)
{
sw.Write(FileDelimiter);
}
}
sw.Write(sw.NewLine);
// Write All Rows to the File
foreach (DataRow dr in d_table.Rows)
{
for (int ir = 0; ir < ColumnCount; ir++)
{
if (!Convert.IsDBNull(dr[ir]))
{
sw.Write(dr[ir].ToString());
//MessageBox.Show(dr[ir].ToString());
}
if (ir < ColumnCount - 1)
{
sw.Write(FileDelimiter);
}
}
sw.Write(sw.NewLine);
}
}
sqlReader.NextResult();
while (sqlReader.Read())
{
d_table.Load(sqlReader);
// Write the Header Row to File
int ColumnCount = d_table.Columns.Count;
for (int ic = 0; ic < ColumnCount; ic++)
{
//MessageBox.Show(d_table.Columns[ic].ToString());
sw.Write(d_table.Columns[ic]);
if (ic < ColumnCount - 1)
{
sw.Write(FileDelimiter);
}
}
sw.Write(sw.NewLine);
// Write All Rows to the File
foreach (DataRow dr in d_table.Rows)
{
for (int ir = 0; ir < ColumnCount; ir++)
{
if (!Convert.IsDBNull(dr[ir]))
{
sw.Write(dr[ir].ToString());
//MessageBox.Show(dr[ir].ToString());
}
if (ir < ColumnCount - 1)
{
sw.Write(FileDelimiter);
}
}
sw.Write(sw.NewLine);
}
}
SQLConnection.Close();
sw.Close();
So far I have tried this but this is not working!!
Any help?
I maintain a nuget package, Sylvan.Data.Csv, that makes this very easy.
string query = "EXEC alpha.dbo.usp_Test_CSV_Report";
using SqlConnection conn = GetSqlConnection();
conn.Open();
using SqlCommand cmd = new SqlCommand(query, conn);
using var sw = File.CreateText("usp_Test_CSV_Report.csv");
using var csvWriter = CsvDataWriter.Create(sw);
using var sqlReader = cmd.ExecuteReader();
bool first = true;
do
{
if (!first)
{
// write the two lines to separate the result sets.
sw.WriteLine();
sw.WriteLine();
}
first = false;
csvWriter.Write(sqlReader);
} while (sqlReader.NextResult());
The library also supports reading multiple result sets out of a single CSV in much the same way:
// tell the reader to expect multiple result sets.
var csvOpts = new CsvDataReaderOptions { ResultSetMode = ResultSetMode.MultiResult };
var csvReader = CsvDataReader.Create("usp_Test_CSV_Report.csv", csvOpts);
do
{
while (csvReader.Read())
{
for(int i = 0; i < csvReader.FieldCount; i++)
{
var value = csvReader.GetString(i);
}
}
} while (csvReader.NextResult());
How can I pass multiple stored procedures to my Scripttask C# code in SSIS and generate output files?
I am successfully able to run one stored procedure from SQL Server database and output one file.
public void Main()
{
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
try
{
string FileNamePart = Dts.Variables["User::FlatFileNamePart"].Value.ToString();
string DestinationFolder = Dts.Variables["User::DestinationFolder"].Value.ToString();
string StoredProcedureFig1_1 = Dts.Variables["User::StoredProcedureFig1_1"].Value.ToString();
string StoredProcedureFig1_2 = Dts.Variables["User::StoredProcedureFig1_2"].Value.ToString();
string FileDelimiter = Dts.Variables["User::FileDelimiter"].Value.ToString();
string FileExtension = Dts.Variables["User::FileExtension"].Value.ToString();
// USE ADO.NET Connection from SSIS Package to get data from table
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(Dts.Connections["localhost.onramps_tacc"].AcquireConnection(Dts.Transaction) as SqlConnection);
// Execute stored procedure and save results in data table
string query1 = "EXEC " + StoredProcedureFig1_1;
// how to run below query too? Stackoverflow question
string query2 = "EXEC " + StoredProcedureFig1_2;
SqlCommand cmd = new SqlCommand(query1, myADONETConnection);
DataTable d_table = new DataTable();
d_table.Load(cmd.ExecuteReader());
myADONETConnection.Close();
string FileFullPath = DestinationFolder + "\\" + FileNamePart + "_" + datetime + FileExtension;
StreamWriter sw = null;
sw = new StreamWriter(FileFullPath, false);
// Write the Header Row to File
String var = d_table + "i";
int ColumnCount = var.Columns.Count;
for (int ic = 0; ic < ColumnCount; ic++)
{
sw.Write(d_table.Columns[ic]);
if (ic < ColumnCount - 1)
{
sw.Write(FileDelimiter);
}
}
sw.Write(sw.NewLine);
// Write all rows to the file
foreach (DataRow dr in d_table.Rows)
{
for (int ir = 0; ir < ColumnCount; ir++)
{
if (!Convert.IsDBNull(dr[ir]))
{
sw.Write(dr[ir].ToString());
}
if (ir < ColumnCount - 1)
{
sw.Write(FileDelimiter);
}
}
sw.Write(sw.NewLine);
}
sw.Close();
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(Dts.Variables["User::LogFolder"].Value.ToString() + "\\" +
"ErrorLog_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
Dts.TaskResult = (int)ScriptResults.Success;
}
Actual:
one stored procedure as input and output the columns and rows in one O/P file OR error file.
Expected:
Accept multiple stored procedures and corresponding generate OutputFiles and error files
Solution:
public void Main()
{
// TODO: Add your code here
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
try
{
//Declare Variables
string FileNamePart = Dts.Variables["User::FlatFileNamePart"].Value.ToString();
string DestinationFolder = Dts.Variables["User::DestinationFolder"].Value.ToString();
string StoredProcedureFig1_1 = Dts.Variables["User::StoredProcedureFig1_1"].Value.ToString();
string StoredProcedureFig1_2 = Dts.Variables["User::StoredProcedureFig1_2"].Value.ToString();
string FileDelimiter = Dts.Variables["User::FileDelimiter"].Value.ToString();
string FileExtension = Dts.Variables["User::FileExtension"].Value.ToString();
//USE ADO.NET Connection from SSIS Package to get data from table
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(Dts.Connections["localhost.onramps_tacc"].AcquireConnection(Dts.Transaction)
as SqlConnection);
//Execute Stored Procedure and save results in data table
string query1 = "EXEC " + StoredProcedureFig1_1;
string query2 = "EXEC " + StoredProcedureFig1_2;
SqlCommand cmd1 = new SqlCommand(query1, myADONETConnection);
SqlCommand cmd2 = new SqlCommand(query2, myADONETConnection);
DataSet dset = new DataSet();
DataTable d_table1 = dset.Tables.Add("Fig1_1");
DataTable d_table2 = dset.Tables.Add("Fig1_2");
d_table1.Load(cmd1.ExecuteReader());
d_table2.Load(cmd2.ExecuteReader());
myADONETConnection.Close();
foreach (DataTable table in dset.Tables)
{
string FileFullPath = DestinationFolder + "\\" + FileNamePart + "_" + table + datetime + FileExtension;
StreamWriter sw = null;
sw = new StreamWriter(FileFullPath, false);
// Write the Header Row to File
int ColumnCount = table.Columns.Count;
for (int ic = 0; ic < ColumnCount; ic++)
{
sw.Write(table.Columns[ic]);
if (ic < ColumnCount - 1)
{
sw.Write(FileDelimiter);
}
}
sw.Write(sw.NewLine);
// Write All Rows to the File
foreach (DataRow dr in table.Rows)
{
for (int ir = 0; ir < ColumnCount; ir++)
{
if (!Convert.IsDBNull(dr[ir]))
{
sw.Write(dr[ir].ToString());
}
if (ir < ColumnCount - 1)
{
sw.Write(FileDelimiter);
}
}
sw.Write(sw.NewLine);
}
sw.Close();
Dts.TaskResult = (int)ScriptResults.Success;
}
}
Table Name in SqlServer DataBase: MyTable
Csv File location : #"d:MyFile.csv"
How to Copy the CSV file "#"d:MyFile.csv" to "MyTable" a table that exists in SQL server database using C# Console application?!!!
I have used following C# code to export from database to CSV file. But how to do the reverse task?!!!
string strConn = "Data Source=MYSERVER;Initial Catalog=Master;Integrated Security=True";
SqlConnection conn = new SqlConnection(strConn);
SqlDataAdapter da = new SqlDataAdapter("select * from QuickBook", conn);
DataSet ds = new DataSet();
da.Fill(ds, "QB");
DataTable dt = ds.Tables["QB"];
StreamWriter sw = new StreamWriter(#"d:MyFile.csv", false);
int iColCount = dt.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
sw.Write(dt.Columns[i]);
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
sw.Close();
}
}
Refer to the Codeproject Link and similar question on this site
First of all you don't want to "Export CSV file to SQL Server", you want to "export CSV file from SQL Server". It's not the same.
I use EntityFramework to generate the model from the date base. You just have to spend two minutes generating the model.
Add new item>Data>ADO.Net Entity Data Model>Generate from database and choose you connection (or make a new one). The next step is select the tables that you want to export.
Finally you just have to go over the properties of you data context (DbSet) and of course you can filter the elements using LINQ.
string path = Path.Combine("D", "MyFile.csv");
using (var dataContext = new MyDataContext())
{
using (StreamWriter sw = new StreamWriter(path))
{
StringBuilder line = new StringBuilder();
foreach (var quickBook in dataContext.QuickBooks)
{
line.AppendFormat("{0};", quickBook.Name);
// Append the other properties (remember the culture with the numbers)
sw.WriteLine(line.ToString());
line.Clear();
}
}
}
One sugestion: You could go over all the properties of a class, in your case "QuickBook":
foreach (PropertyInfo property in typeof(QuickBook).GetProperties())
{
object value = property.GetValue(quickBook, null);
if (value == null)
line.Append(";");
else
line.AppendFormat("{0};", value);
}
if (line.Length > 0) //Removes the last ';'
line.Remove(line.Length - 1, 1);
The reverse task using EntityFramework could be like this:
string path = Path.Combine("D", "MyFile.csv");
using (var dataContext = new MyDataContext())
{
using (StreamReader stream = new StreamReader(path))
{
string line;
while ((line = stream.ReadLine()) != null)
{
string[] columns = stream.ReadLine().Split(';');
QuickBook item = new QuickBook();
item.Name = columns[0];
// And so on with the other properties...
dataContext.QuickBooks.Add(item);
}
}
dataContext.SaveChanges();
}
I am looking for a way to create, modify, read .xlsx files in C# without installing Excel or creating files on the server before giving to the user to download.
I found NPOI http://npoi.codeplex.com/ which looks great but supports .xls not .xlsx
I found ExcelPackage http://excelpackage.codeplex.com/ which looks great but has the additional overhead of creating the file on the server before it can be sent to the user.
Does anyone know of a way around this?
I found EPPlus http://epplus.codeplex.com but I am not not certain if this requires creation of a file on the server before it can be sent to the user?
I am pretty new to this so any guidance/examples etc., would be very much appreciated.
With EPPlus it's not required to create file, you can do all with streams, here is an example of ASP.NET ashx handler that will export datatable into excel file and serve it back to the client :
public class GetExcel : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
var dt = DBServer.GetDataTable("select * from table");
var ms = GetExcel.DataTableToExcelXlsx(dt, "Sheet1");
ms.WriteTo(context.Response.OutputStream);
context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
context.Response.AddHeader("Content-Disposition", "attachment;filename=EasyEditCmsGridData.xlsx");
context.Response.StatusCode = 200;
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
public static MemoryStream DataTableToExcelXlsx(DataTable table, string sheetName)
{
var result = new MemoryStream();
var pack = new ExcelPackage();
var ws = pack.Workbook.Worksheets.Add(sheetName);
int col = 1;
int row = 1;
foreach (DataRow rw in table.Rows)
{
foreach (DataColumn cl in table.Columns)
{
if (rw[cl.ColumnName] != DBNull.Value)
ws.Cells[row, col].Value = rw[cl.ColumnName].ToString();
col++;
}
row++;
col = 1;
}
pack.SaveAs(result);
return result;
}
}
http://msdn.microsoft.com/en-us/library/cc850837.aspx
Try to use this code to export the data to excel, may it ll help
public static void DataSetsToExcel(DataSet dataSet, string filepath)
{
try
{
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties=Excel 12.0 Xml;";
string tablename = "";
DataTable dt = new DataTable();
foreach (System.Data.DataTable dataTable in dataSet.Tables)
{
dt = dataTable;
tablename = dataTable.TableName;
using (OleDbConnection con = new OleDbConnection(connString))
{
con.Open();
StringBuilder strSQL = new StringBuilder();
strSQL.Append("CREATE TABLE ").Append("[" + tablename + "]");
strSQL.Append("(");
for (int i = 0; i < dt.Columns.Count; i++)
{
strSQL.Append("[" + dt.Columns[i].ColumnName + "] text,");
}
strSQL = strSQL.Remove(strSQL.Length - 1, 1);
strSQL.Append(")");
OleDbCommand cmd = new OleDbCommand(strSQL.ToString(), con);
cmd.ExecuteNonQuery();
for (int i = 0; i < dt.Rows.Count; i++)
{
strSQL.Clear();
StringBuilder strfield = new StringBuilder();
StringBuilder strvalue = new StringBuilder();
for (int j = 0; j < dt.Columns.Count; j++)
{
strfield.Append("[" + dt.Columns[j].ColumnName + "]");
strvalue.Append("'" + dt.Rows[i][j].ToString().Replace("'", "''") + "'");
if (j != dt.Columns.Count - 1)
{
strfield.Append(",");
strvalue.Append(",");
}
else
{
}
}
if (strvalue.ToString().Contains("<br/>"))
{
strvalue = strvalue.Replace("<br/>", Environment.NewLine);
}
cmd.CommandText = strSQL.Append(" insert into [" + tablename + "]( ")
.Append(strfield.ToString())
.Append(") values (").Append(strvalue).Append(")").ToString();
cmd.ExecuteNonQuery();
}
con.Close();
}
}
}
catch (Exception ex)
{
}
}