Is Spire.XLS C# support HDR - option when Excel file has no header file? - spire.xls

Is Spire.XLS C# support HDR - option when Excel file has no header file ? I have Excel file without header file. This is resolved in OLEDB driver in connection string HDR="No" Option.

You can use the ExportDataTable(CellRange range, bool exportColumnNames) method of Spire.Xls.Worksheet class to read worksheet data into a data table and determine whether to export the first row in the worksheet range as header row in the data table.
Example:
private void button1_Click(object sender, EventArgs e)
{
Workbook workbook = new Workbook();
workbook.LoadFromFile("Input.xlsx");
Worksheet sheet = workbook.Worksheets[0];
DataTable dt = sheet.ExportDataTable(sheet.Range, false);
dataGridView1.DataSource = dt;
}

Related

Store result of ExcecuteNonQuery() result into GridView in ASP.NET

I am looking suggestions for store my ExecuteNonQuery() into .csv file.
I am trying to execute .sql file in ASP.NET and try to store it's result into csv file.
Can anyone know how to do this?
My code snippet:
protected void Btn_result_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
string auctionFacilityProfitAdjustment = File.ReadAllText(#"E:\Profit Adjustment Data\Auction Facility Profit Adjustment.sql");
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
Server server = new Server(new ServerConnection(connection));
int count = server.ConnectionContext.ExecuteNonQuery(auctionFacilityProfitAdjustment);
}
And result stores into GridView. And then csv file.
For eg. My result is 2 affected rows.
So, I want to store it into GridView like:
101 ABC 123467890
102 HHG 9876543210
103 JJL 3794826892
Like wise.

How to import excel to sql server with some column values transforming into row using asp.net?

I want to import an excel file to sql server using asp.net with C#.
The user upload the file from the web page by using file upload control.
here is the code.
here I used outer apply to transform columns to row.
when I run the code the below error coming.
IErrorInfo.GetDescription failed with E_FAIL(0x80004005).
protected void BtnUpload_Click(object sender, EventArgs e)
{
string excelPath = Server.MapPath("~/Files/") + Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(excelPath);
string conString = string.Empty;
string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
switch (extension)
{
case ".xls": //Excel 97-03
conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx": //Excel 07 or higher
conString = ConfigurationManager.ConnectionStrings["Excel07+ConString"].ConnectionString;
break;
}
conString = string.Format(conString, excelPath);
using (OleDbConnection excel_con = new OleDbConnection(conString))
{
excel_con.Open();
string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();
DataTable dtExcelData = new DataTable();
string st = “Select [sno], [Id],[country],[Qtr]=case(substring([Qtr],1,2) as nvarchar(4)), [value] from [“+sheet1+”] outer apply(values((N'Q1',Q1),(N'Q2',Q2)) P(Qtr,value)”;
using (OleDbDataAdapter oda = new OleDbDataAdapter(st, excel_con))
{
oda.Fill(dtExcelData);
}
excel_con.Close();
string consString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(consString))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
{
//Set the database table name
sqlBulkCopy.DestinationTableName = "[dbo].[exceldemo]";
con.Open();
sqlBulkCopy.WriteToServer(dtExcelData);
con.Close();
lblUpload.Text = "Uploaded Succesfully";
}
Below is the format. Please check it.
http://i61.tinypic.com/217pk0.jpg
I have also tried with UNPIVOT also.
Please tell me if any thing wrong in the above code and give suggestions to overcome this problem.
Thank you very much in advance.
You will need to be more precise on what you want to achieve. Are you working in C# or VB.Net? Will the user upload the file from the web page? What have you tried so far?
One way to import an Excel file to SQL Server using ASP.NET is to upload the file to your server with a FileUpload. The user will then be able to choose the file he wants to import.
Then, you will want to read the data in that Excel file and put it in a Datatable. It will enable you to work with it in your code behind. Here is a good example on how to read the data from the Excel file ( http://www.codeproject.com/Tips/509179/Read-Excel-File-into-DataSet-in-ASP-NET-Using-Csha). It is similar to reading that of a database, but you connect to your Excel file.
Now that your data is in the datatable, you will be able to do the manipulations that you want.
Afterwards, you can write your data to your SQL Server in many different ways, it depends on how you write to your database. ADO, NHibernate, EF, Stored Procedures, Dynamic SQL? You can also do a BulkCopy. It will copy all the data from your datatable into the database without having the need to iterate through all the rows of your datatable. You will need to map your columns and make sure your datatable is formatted correctly. (https://msdn.microsoft.com/en-us/library/ex21zs8x(v=vs.110).aspx)
Please update your question with more information and what you have tried so far so we can give you a more specific answer.

Export sqldatasource to excel not just list or gridview

I'm trying to export my listview, but not just the visible listview, I want to export the entire contents of the sqldatasource. The query returns 20 columns, only a small set (5) are displayed on the listview. Is there a way i can export the entire 20 columns to excel file?
I have this so far:
protected void ExportToExcel(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition", "attachment;filename=SearchResults.xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
this.EnableViewState = false;
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
//I want to chagne this:
this.ResultsListView.RenderControl(htmlTextWriter);
Response.Write(stringWriter.ToString());
Response.End();
}
instead of this line:
this.ResultsListView.RenderControl(htmlTextWriter);
I would like to do something like:
this.sqldatasource.RenderControl(htmlTextWriter);
But obviously SqlDataSource doesn't have a RenderControl method. Is there a clean way of going about this?
You can create a DataTable from the DataView returned by the SqlDataSource and export that to Excel. The resulting DataTable will contain all the columns.
Example:
DataTable dt = ((DataView) this.sqldatasource.Select(DataSourceSelectArguments.Empty)).ToTable();
Now take this DataTable and export that. Google export DataTable to Excel.
If you are fine with using third-party libraries, look into EPPLUS. You can export a DataTable to Excel in, literally, 2 lines of code. The rest would be the code to set the headers and flush the Response.
Here's an example: http://epplus.codeplex.com/wikipage?title=WebapplicationExample
I prefer to use CSV rather than excel for plain data, but the new version of Excel does have the advantage of compression.
You can use the OpenXMLSDK to directly export to XLSX or the FileHelpers library to export to CSV.

Opening a word doc from sharepoint, replace text and stream to user

I want to be able to store a template word document in Sharepoint, and use it as a base for spitting out a word doc containing data injected into the template.
I can get the text of my word doc using code as follows:
SPSite sc = SPContext.Current.Site;
SPWeb web = sc.AllWebs["MySite"];
string contents = web.GetFileAsString("Documents/MyTemplateWord.doc");
web.Dispose();
Then I can string replace on the "contents" variable. This works fine.
I now want to "open" this new content as a word doc.
My code for this is as follows:
string attachment = "attachment; filename=MyWord.doc";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "text/ms-word";
HttpContext.Current.Response.Write(outputText);
HttpContext.Current.Response.End();
I'm getting an error though, and not sure how to resolve it.
Error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled. Details: Error parsing near 'ࡱ>
Now clearly it has issues parsing the "string" content.
What am I doing wrong? Is there a different way I should be doing this?
You are not reading a string, you are converting binary data to a string.
(Rembember that a docx is a zip file containing xml data).
The nature of your approach to replacing the text is flawed in this regard.
If it were not for the desire to find/replace the text, I would recommend
using(SPWeb web = new SPSite("<Site URL>").OpenWeb())
{
SPFile file = web.GetFile("<URL for the file>");
byte[] content = file.OpenBinary();
HttpContext.Current.Response.Write(content);
}
http://support.microsoft.com/kb/929265
Using a BinaryWrite to get the data to your page.
However, because you are using Word, I would recommend loading the document into an instance of the Microsoft.Office.Interop.Word objects.
However, using Word interop can be a bit of a time vampire.
1- add docx assembly to your shaepoint package https://docx.codeplex.com
2- using Novacode;
3- note the following sample download button
protected void ButtonExportToWord_Click(object sender, EventArgs e)
{
byte[] bytesInStream;
using (Stream tplStream =
SPContext.Current.Web.GetFile("/sitename/SiteAssets/word_TEMPLATE.docx").OpenBinaryStream())
{
using (MemoryStream ms = new MemoryStream((int)tplStream.Length))
{
CopyStream(tplStream, ms);
ms.Position = 0L;
DocX doc = DocX.Load(ms);
ReplaceTextProxy(doc,"#INC#", "11111111");
doc.InsertParagraph("This is my test paragraph");
doc.Save();
bytesInStream = ms.ToArray();
}
}
Page.Response.Clear();
Page.Response.AddHeader("Content-Disposition", "attachment; filename=" +
CurrentFormId + ".docx");
Page.Response.AddHeader("Content-Length", bytesInStream.ToString());
Page.Response.ContentType = "Application/msword";
Page.Response.BinaryWrite(bytesInStream);
Page.Response.Flush();
Page.Response.Close();
//Page.Response.End();// it throws an error
}
private void ReplaceTextProxy(DocX doc, string oldvalue, string newValue)
{
doc.ReplaceText(oldvalue,newValue,false, RegexOptions.None, null, null,
MatchFormattingOptions.SubsetMatch);
}

Serving a word document generated using Open XML from an asp.net webpage

I'm trying to serve a word document (docx) from an asp.net page using the following code
protected void Page_Load(object sender, EventArgs e)
{
MemoryStream document = new MemoryStream();
using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(document, WordprocessingDocumentType.Document))
{
MainDocumentPart mainPart = wordDoc.AddMainDocumentPart();
SetMainDocumentContent(mainPart);
}
string fileName = "MsWordSample.docx";
Response.AppendHeader("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
Response.AppendHeader("Content-disposition", "attachment; filename=" + fileName);
Response.OutputStream.Write(document.ToArray(), 0, document.ToArray().Length);
}
public static void SetMainDocumentContent(MainDocumentPart part)
{
const string docXml =
#"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<w:document xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main"">
<w:body>
<w:p>
<w:r>
<w:t>Hello world!</w:t>
</w:r>
</w:p>
</w:body>
</w:document>";
using (Stream stream = part.GetStream())
{
byte[] buf = (new UTF8Encoding()).GetBytes(docXml);
stream.Write(buf, 0, buf.Length);
}
}
but I get the following message when trying to open the file: "the file {file name} cannot be opened because there are problems with the content"
I then get an option to recover the document which actually fixes the document.
Am I leaving something out?
That error message you're getting means the underlying XML doesn't conform to the schema in some way. This could be caused by having elements in the wrong order, forgetting a parent to an element, adding a wrong attribute, forgetting required elements, etc. I recommend downloading the Open XML SDK 2.0 Productivity Tool, create a test file, and then opening that up to see what the XML should be. Then compare that file to the one you are creating to see what is missing.

Resources