C# create/modify/read .xlsx files - c#

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)
{
}
}

Related

SSIS split flat file(TXT) to multiple based on the number of records it has

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!

Getting System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near 'OfficeOpenXml'. Error message

I'm trying to import Excel sheet data into the DB via SSIS script task, I'm continuously getting the above error message.
The Excel file has 3 sheet, and we have separate table for each sheet of that Excel file in the database.
Also I'm not getting any error in the region Namespaces.
Can anyone help, what I'm missing here?
public void Main()
{
try
{
string filePath;
filePath = Dts.Variables["FilePath1"].Value.ToString();
ReadXLS(filePath);
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
Dts.TaskResult = (int)ScriptResults.Success;
}
}
public void ReadXLS(string FilePath)
{
FileInfo existingFile = new FileInfo(FilePath);
using (ExcelPackage package = new ExcelPackage(existingFile))
{
string eachVal = "";
int wsheet = package.Workbook.Worksheets.Count;
for (int sheet = 0; sheet<wsheet; sheet++)
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[sheet];
string SheetNames = worksheet.Names.ToString();
int rowCount = worksheet.Dimension.End.Row;
int colCount = worksheet.Dimension.End.Column;
for (int row = 2; row <= rowCount; row++)
{
string queryString = "Insert into [Billing_]" + SheetNames + "values(";
queryString += "(";
for (int col = 1; col <= colCount; col++)
{
eachVal = worksheet.Cells[row, col].Value?.ToString().Trim();
queryString += "'" + eachVal + "',";
}
queryString = queryString.Remove(queryString.Length - 1, 1);
queryString += ")";
runQuery(queryString);
}
}
private void runQuery(string QueryString)
{
string connectionString = #"Data Source = ./; Initial Catalog = Testing; Integrated Security = SSPI;";
string commandText = QueryString;
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(commandText, conn))
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}

How can I pass multiple stored procedures to my script task C# code in SSIS and generate output files?

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;
}
}

How do you programmatically check if a spreadsheet has headers in C#

I am creating a winform application where every day, a user will select a xlsx file with the day's shipping information to be merged with our invoicing data.
The challenge I am having is when the user does not download the xlsx file with the specification that the winform data requires. (I wish I could eliminate this step with an API connection but sadly I cannot)
My first step is checking to see if the xlsx file has headers to that my file path is valid
Example
string connString = "provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + *path* + "';Extended Properties='Excel 12.0;HDR=YES;';";
Where path is returned from an OpenFileDialog box
If the file was chosen wasn't downloaded with headers the statement above throws an exception.
If change HDR=YES; to HDR=NO; then I have trouble identifying the columns I need and if the User bothered to include the correct ones.
My code then tries to load the data into a DataTable
private void loadRows()
{
for (int i = 0; i < deliveryTable.Rows.Count; i++)
{
DataRow dr = deliveryTable.Rows[i];
int deliveryId = 0;
bool result = int.TryParse(dr[0].ToString(), out deliveryId);
if (deliveryId > 1 && !Deliveries.ContainsKey(deliveryId))
{
var delivery = new Delivery(deliveryId)
{
SalesOrg = Convert.ToInt32(dr[8]),
SoldTo = Convert.ToInt32(dr[9]),
SoldName = dr[10].ToString(),
ShipTo = Convert.ToInt32(dr[11]),
ShipName = dr[12].ToString(),
};
Which all works only if the columns are in the right place.
If they are not in the right place my thought is to display a message to the user to get the right information
Does anyone have any suggestions?
(Sorry, first time posting a question and still learning to think through it)
I guess you're loading the spreadsheet into a Datatable? Hard to tell with one line of code. I would use the columns collection in the datatable and check to see if all the columns you want are there. Sample code to enumerate the columns below.
private void PrintValues(DataTable table)
{
foreach(DataRow row in table.Rows)
{
foreach(DataColumn column in table.Columns)
{
Console.WriteLine(row[column]);
}
}
}
private void GetExcelSheetForUpload(string PathName, string UploadExcelName)
{
string excelFile = "DateExcel/" + PathName;
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
try
{
DataSet dss = new DataSet();
String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=True;Extended Properties=Excel 12.0 Xml;Data Source=" + PathName;
objConn = new OleDbConnection(connString);
objConn.Open();
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return;
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
if (i == 0)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + excelSheets[i] + "]", objConn);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
oleda.Fill(dss, "TABLE");
}
i++;
}
grdExcel.DataSource = dss.Tables[0].DefaultView;
grdExcel.DataBind();
lblTotalRec.InnerText = Convert.ToString(grdExcel.Rows.Count);
}
catch (Exception ex)
{
ViewState["Fuletypeidlist"] = "0";
grdExcel.DataSource = null;
grdExcel.DataBind();
}
finally
{
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}
if (grdExcel.HeaderRow.Cells[0].Text.ToString() == "CODE")
{
GetExcelSheetForEmpl(PathName);
}
else
{
divStatusMsg.Style.Add("display", "");
divStatusMsg.Attributes.Add("class", "alert alert-danger alert-dismissable");
divStatusMsg.InnerText = "ERROR !!... Upload Excel Sheet in header Defined Format ";
}

Dot is implicitly converted into hash while converting data from Excel file to XML

I have succeeded in creating XML file from an Excel file using the following C# code:
protected void Button5_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
OleDbConnection ole = new OleDbConnection();
string s = Server.MapPath("../admin/ProductOptions");
s = s + "\\" + FileUpload1.FileName;
System.IO.File.Delete(s);
FileUpload1.PostedFile.SaveAs(s);
string path = s;
ole.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + path + ";" + "Extended Properties=" + "\"" + "Excel 12.0;HDR=YES;" + "\"";
OleDbCommand command = new OleDbCommand("select * from[SHEET1$]", ole);
DataSet ds = new DataSet();
OleDbDataAdapter adapter = new OleDbDataAdapter(command);
adapter.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
GridView1.Visible = true;
string filepath = Server.MapPath("ProductOptions") + "\\" + DDLproduct.SelectedValue + ".xml";
Session["ss"] = ds;
write_to_xml(ds,filepath);
}
else
{
Label2.Visible = true;
Label2.Text="[Please Select a file]";
}
}
But the problem is when this code is converting the Excel Data to XML data, then dots are itself converted into Hash(Only First Row). I know the reason but don't know the solution.
It`s happening because of dots in Excel file when converted into XML tags them implicitly converted to HASH.......
Kindly suggest me, how can I stop this conversion?
Finally got the solution:
When OLEDB Adapter fills the data in DataSet, it converts DOT into HASH.
Now I have stored that data into a DataTable(dt) and then accessed the column name and replace HASH with DOT (using Replace method of String) and create a new DataTable(dt2) with new column names.
After this using two for loops, I have inserted data from first DataTable(dt) to new Datatable(dt2).
(*one loop for rows and another one for columns)
Finally bind the grid with new DataTable(dt2)
Following is the full code for that function:
if (FileUpload1.HasFile)
{
OleDbConnection ole = new OleDbConnection();
string s = Server.MapPath("../admin/ProductOptions");
s = s + "\\" + FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(s);
string path = s;
ole.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + path + ";" + "Extended Properties=" + "\"" + "Excel 12.0;HDR=YES;IMEX=2;READONLY=FALSE;" + "\" ";
OleDbCommand command = new OleDbCommand("select * from[SHEET1$]", ole);
DataSet ds = new DataSet();
OleDbDataAdapter adapter = new OleDbDataAdapter(command);
adapter.Fill(ds);
DataTable dt = (DataTable)ds.Tables[0];
DataTable dt2 = new DataTable("dt2");
Session["dt"] = null;
for (int i = 0; i < dt.Columns.Count; i++)
{
string s2 = dt.Columns[i].ToString();
s2 = s2.Replace("#", ".");
string ProductName = s2.ToString();
if (Session["dt"] == null)
{
DataColumn dCol1 = new DataColumn(ProductName, typeof(System.String));
dt2.Columns.Add(dCol1);
}
}
for (int i = 0; i < dt.Rows.Count; i++)
{
dt2.Rows.Add();
for (int x = 0; x < dt.Columns.Count; x++)
{
dt2.Rows[i][x] = dt.Rows[i][x];
}
}
System.IO.File.Delete(s);
GridView1.DataSource = dt2;
GridView1.DataBind();
GridView1.Visible = true;
string filepath = Server.MapPath("ProductOptions") + "\\" + DDLproduct.SelectedValue + ".xml";
// Session["ss"] = ds;
write_to_xml(dt2,filepath);
}
else
{
Label2.Visible = true;
Label2.Text="[Please Select a file]";
}
Following is the code for write_to_xml() :
public void write_to_xml(DataTable dt, string path)
{
dt.WriteXml(path);
}
Any query or alternative solution would be appreciated... :)
Turn your headers off by HDR=No in your connection string and get your job done.
Before feeding them back to excel with HDR=Yes replace .s with #s using regex or any tool you want in the first row.
Instead of your solution I use Encoding.UTF8 in this way:
using (var fs = new FileStream(xmlFile, FileMode.CreateNew))
{
using (var xw = new XmlTextWriter(fs, Encoding.UTF8))
{
ds.WriteXml(xw);
}
}
And had no problem, this also converts < to < and > to >.

Categories