Any body say how can we convert a data-table to XML format.
I tried the below one but is is not saving or exporting the data
XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection<DLReports.FCBuySellDetail>));
using (StreamWriter wr = new StreamWriter("customers.xml"))
{
xs.Serialize(wr, DetailReportFCBuySell1);
}
DataTable dtSample = new DataTable();
dtSample.WriteXml(fileName); //Pass the path of the XML file.
Related
Following is the ActionResult Method created to return EXCEl File, which works fine. However, there is a problem that the content for each column is too large that the rows are mal-formed, which means there are wide blank-spaces between rows.
Following is the ActionResult code.
public ActionResult ImportExecelFile(int appNo)
{
List<PendingApproval> pendings = objPA.GetPendingApprovals(appNo.ToString());
string xml = String.Empty;
XmlDocument xmlDoc = new XmlDocument();
XmlSerializer xmlSerializer = new XmlSerializer(pendings.GetType());
using (MemoryStream xmlStream = new MemoryStream())
{
xmlSerializer.Serialize(xmlStream, pendings);
xmlStream.Position = 0;
xmlDoc.Load(xmlStream);
xml = xmlDoc.InnerXml;
}
//Create file
string fileName = "Pending_Approvals";
fileName += string.Format("-{0}", DateTime.Now.ToString("yyyy-MM-dd"));
fileName += ".xls";
byte[] fileContents = Encoding.UTF8.GetBytes(xml);
return File(fileContents, "application/vnd.ms-excel", fileName);
}
You're not creating an Excel file - you're creating XML and saving it with an .xls extension. Excel will try its best to open it, although it's probably going to raise a warning to the user because it's not really an Excel file.
Excel files can contain formatting, including column widths. Data serialized as XML will not have that. So there's really no way to control how Excel displays the XML.
You can accomplish what you're trying to do using a library like EPPlus that creates Excel workbooks using OpenXML. But if you're just saving XML as .xls then you won't have any control over formatting. (I'm amazed it opens at all, but I tested saving an XML file as .xls and it worked except for the warning message.)
This problem is most likely pretty simple, but I am making a dataset and trying to save it to a file using XMLTextWriter
Now when i save my dataset and then attempt to read it will read the table names but shows the rows as 0? So it seems my writer is not writing the rows of the table?
Anyone know how I can fix this?
public static DataSet liveData = new DataSet();
public static DataTable players = new DataTable("Players");
public static void WriteSchemaWithXmlTextWriter()
{
// Set the file path and name. Modify this for your purposes.
string filename = "Schema.xml";
// Create a FileStream object with the file path and name.
System.IO.FileStream stream = new System.IO.FileStream(filename, System.IO.FileMode.Create);
// Create a new XmlTextWriter object with the FileStream.
System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(stream, System.Text.Encoding.Unicode);
// Write the schema into the DataSet and close the reader.
liveData.WriteXmlSchema(writer);
writer.Close();
}
public static void ReadSchemaFromXmlTextReader()
{
// Set the file path and name. Modify this for your purposes.
string filename = "Schema.xml";
// Create a FileStream object with the file path and name.
System.IO.FileStream stream = new System.IO.FileStream(filename, System.IO.FileMode.Open);
// Create a new XmlTextReader object with the FileStream.
System.Xml.XmlTextReader xmlReader = new System.Xml.XmlTextReader(stream);
// Read the schema into the DataSet and close the reader.
liveData.ReadXmlSchema(xmlReader);
Console.WriteLine("y: {0}", liveData.Tables["Players"].Rows.Count);
xmlReader.Close();
}
Thank you for your help in advance :)
You are writing the schema, which is the layout/structure of the Xml, rather than the actual content.
You need to use DataSet.WriteXml ...
https://msdn.microsoft.com/en-us/library/ms135426%28v=vs.110%29.aspx
... instead!
I tried to write to CSV file using CsvHelper in C#.
This is the link to the library http://joshclose.github.io/CsvHelper/
I used the code in web site.
Here is my code:
var csv = new CsvWriter(writer);
csv.Configuration.Encoding = Encoding.UTF8;
foreach (var value in valuess)
{
csv.WriteRecord(value);
}
It writes only a part of data to csv file.
Last rows were missing.
Could you please help with this.
You need to flush the stream. The Using statement will flush when out of scope.
using (TextWriter writer = new StreamWriter(#"C:\test.csv", false, System.Text.Encoding.UTF8))
{
var csv = new CsvWriter(writer);
csv.WriteRecords(values); // where values implements IEnumerable
}
when, I added this code after the loop code is working well
var csv = new CsvWriter(writer);
csv.Configuration.Encoding = Encoding.UTF8;
foreach (var value in valuess)
{
csv.WriteRecord(value);
}
writer.Close();
The problem occurred because I did not close the Connection
Assuming that writer is some kind of TextWriter, you should add a call to flush the contents before closing the writer:
writer.Flush()
If the last lines are missing, this is the most likely reason.
Adding to #greg's answer:
using (var sr = new StreamWriter(#"C:\out.csv", false, Encoding.UTF8)) {
using (var csv = new CsvWriter(sr)) {
csv.WriteRecords(values);
}
}
I have an dataset which i need to convert to xml with encoding="UTF-8 " specifiedin the xml file
SqlConnection con = new SqlConnection(dbconn);
con.Open();
SqlDataAdapter cmd1 = new SqlDataAdapter("select * from employee", con);
DataSet ds = new DataSet();
cmd1.Fill(ds);
string strFileName = #"E:\Dif.xml";
MemoryStream memStream = new MemoryStream();
StreamWriter writer = new StreamWriter(memStream, Encoding.UTF8);
ds.WriteXml(writer, XmlWriteMode.WriteSchema);
i see no xml file been written,
i wante dteh xml file to be written in this format in the heading
<?xml version="1.0" encoding="utf-8" ?>
so what is teh setting that i should be doing while converting dataset to xml.
please help me out, i ma using vs2003,.net 1.1 framework
thanks
prince
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
using (XmlWriter xmlWriter = XmlWriter.Create(strFileName, settings))
{
ds.WriteXml(xmlWriter);
xmlWriter.Close();
}
Use this can write xml with encoding:
<?xml version="1.0" encoding="utf-8"?>
As per Alex's suggestion, here is my comment as an answer:
Try using FileStream instead of MemoryStream: Your code should look like this:
FileStream fs =new FileStream(strFileName, FileMode.CreateNew, FileAccess.Write, FileShare.None);
StreamWriter writer = new StreamWriter(fs, Encoding.UTF8);
ds.WriteXML(writer, XMLWriteMode.WriteSchema);
But also, please take a look at his anwer too, maybe the answer is a combination of both our answers.
I used flying19880517s answer and converted it to an extension method. To get the same result as the original WriteXml method I added Indent = true (otherwise your get the xml without newlines / spaces.
public static void WriteXml(this DataSet ds, string fileName, Encoding encoding)
{
using (var writer = XmlWriter.Create(fileName,
new XmlWriterSettings { Encoding = encoding, Indent = true, }))
ds.WriteXml(writer);
}
Have you tried XmlWriteMode.IgnoreSchema?
Taken from http://msdn.microsoft.com/en-us/library/system.data.xmlwritemode.aspx for XmlWriteMode.WriteSchema:
Writes the current contents of the
DataSet as XML data with the
relational structure as inline XSD
schema. If the DataSet has only a
schema with no data, only the inline
schema is written. If the DataSet does
not have a current schema, nothing is
written.
You are writing to a memory stream. Use a FileStream if you want output to disk.
Regards, Morten
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Create Excel (.XLS and .XLSX) file from C#
I have some code that generates a zip file that contains multiple CSV files and streams it back to the user (no file is saved on the server). However, I want to create an excel workbook instead (can be traditional xls or Office Open XML xlsx format) with each CSV 'file' being a spreadsheet.
How can I do this, without resorting to Office Automation on the server or a commercial 3rd party component?
You can use OleDB to generate simple tables in Excel files.
Note that you will need to generate a temp file on the server.
Example.
Note that their example is incorrect and needs to use an OleDbConnectionStringBuilder, like this:
OleDbConnectionStringBuilder builder = new OleDbConnectionStringBuilder();
if (isOpenXML)
builder.Provider = "Microsoft.ACE.OLEDB.12.0";
else
builder.Provider = "Microsoft.Jet.OLEDB.4.0";
builder.DataSource = fileName;
builder["Extended Properties"] = "Extended Properties=\"Excel 8.0;HDR=YES;\""
using (var con = new OleDbConnection(builder.ToString())) {
...
}
The XML format for Excel is quite simple and there's absolutely no need to do any automation.
The full reference is up on MSDN: http://msdn.microsoft.com/en-us/library/aa140066(office.10).aspx
Response.ContentType = "application/vnd.ms-excel";
The ContentType property specifies the HTTP content type for the response. If no ContentType is specified, the default is text/HTML.
Get all your data in a DataGrid and then get it from it can be done with:
DataGrid.RenderControl
Outputs server control content to a provided HtmlTextWriter object and stores tracing information about the control if tracing is enabled.
SqlConnection cn = new SqlConnection("yourconnectionstring");
cn.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Users", cn);
DataTable dt = new DataTable();
da.Fill(dt);
DataGrid dg = new DataGrid();
dg.DataSource = dt;
dg.DataBind();
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
dg.RenderControl(hw);
cn.Close();
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
this.EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
You can write the excel xml by yourself. Here is a nice lib for the task, maybe it is something for you.
// Edit
Link: http://www.carlosag.net/Tools/ExcelXmlWriter/Generator.aspx