I want to import excel to devexpress grid.
When I runing in my PC, It work well.
But "Invalid file signature" error occurs in customer's PC.
So I get the customer's excel file(.xlsx) and open it my PC.
No error occurs in my PC. ...Why?
Here, my code to open excel file.
Dim stream As FileStream = File.Open(filePath, FileMode.Open, FileAccess.Read)
If UCase(strExt) = "XLS" Then
Dim excelReader As IExcelDataReader = ExcelReaderFactory.CreateBinaryReader(stream)
Dim excelDsConf As ExcelDataSetConfiguration = New ExcelDataSetConfiguration()
excelDsConf.ConfigureDataTable = Function() New ExcelDataTableConfiguration() With {
.UseHeaderRow = True
}
DtSet = excelReader.AsDataSet(excelDsConf)
DtSet.Tables(0).TableName = "ExcelData"
Else 'XLSX
Dim excelReader As IExcelDataReader = ExcelReaderFactory.CreateOpenXmlReader(stream)
Dim excelDsConf As ExcelDataSetConfiguration = New ExcelDataSetConfiguration()
excelDsConf.ConfigureDataTable = Function() New ExcelDataTableConfiguration() With {
.UseHeaderRow = True
}
DtSet = excelReader.AsDataSet(excelDsConf)
DtSet.Tables(0).TableName = "ExcelData"
End If
.Netframework is 4.0
Why "Invalid file signature" error occur in customer's PC?
What should I check on the customer's PC?
Related
I read an excel file (.xlsm; password-protected) with a vb.net application. I use the following interfaces:
System.IO.filestream
Syncfusion.XlsIO (NuGet)
That works, but I want to open it in ReadOnly-Mode, so that any other people can use this file with MS Office (write, save, ...).
Code:
Imports Syncfusion.XlsIO
Private SyncEE As Syncfusion.XlsIO.ExcelEngine
Private SyncWB As Syncfusion.XlsIO.IWorkbook
Private SyncFS As System.IO.FileStream
Public Sub new
SyncEE = New ExcelEngine
SyncFS = New FileStream(PathFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
SyncEE.Excel.DefaultVersion = ExcelVersion.Excel2016
SyncWB = SyncEE.Excel.Workbooks.Open(SyncFS, ExcelParseOptions.Default, openReadOnly, password)
SyncWB.Unprotect(password)
SyncWB = SyncEE.Excel.Workbooks.Open(SyncFS, ExcelOpenType.Automatic)
' read....
'discard
SyncWB.Close()
SyncWB = Nothing
SyncEE.Dispose()
SyncEE = Nothing
SyncFS.Dispose()
SyncFS = Nothing
End Sub
I tried it step by step and found out that i block the file at row:
SyncFS = New FileStream(PathFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
and I release the file at the 'discard' rows.
Blocking means that no one can edit and save the excel-file manually in MS Excel while I read it.
Greetings from Syncfusion.
You are blocking the file on loading the file using FileStream, as mentioned by you and you are discarding the FileStream object only at the end of your entire program. You can discard the FileStream object immediately after loading it into a workbook object so that others can use the file with MS Office (write, save, …) while you are reading it. Hence, we have modified your code as below to achieve your requirement.
Code snippet:
Private Sub new
SyncEE = New ExcelEngine
SyncFS = New FileStream(PathFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
SyncEE.Excel.DefaultVersion = ExcelVersion.Excel2016
SyncWB = SyncEE.Excel.Workbooks.Open(SyncFS, ExcelParseOptions.Default, openReadOnly, password)
'Discard FileStream
SyncFS.Dispose()
SyncFS = Nothing
' read....
'discard
SyncWB.Close()
SyncWB = Nothing
SyncEE.Dispose()
SyncEE = Nothing
End Sub
Note: I work for Syncfusion.
Regards,
Shamini
try
{
FileInfo resultFile = new FileInfo(#"C:\\Users\\350154\\Desktop\\vb workouts\\testsample.xlsx");
if (resultFile.Exists)
{
resultFile.Delete();
}
ExcelPackage masterPackage = new ExcelPackage(new FileInfo(#"C:\\Users\\350154\\Desktop\\vb workouts\\testsample.xlsx"));
ExcelPackage pckg = new ExcelPackage(new FileInfo(#"C:\\Users\\350154\\Desktop\\vb workouts\\y.xlsx"));
string workSheetName = pckg.Workbook.Worksheets[1].Name;
masterPackage.Workbook.Worksheets.Add(workSheetName, pckg.Workbook.Worksheets[1]);
masterPackage.Workbook.Worksheets.Add("test");
masterPackage.SaveAs(new FileInfo(#"C:\\Users\\350154\\Desktop\\vb workouts\\testsample.xlsx"));
}catch(excption e){
console.writeline();
}
Hi,Am using Epplus to copy a worksheet from a workbook to a new workbook and create as a ne worksheet.My code is above.I am using Epplus4.0 .But am not able to process my code.Error is arising:Error Saving File
please help me to solve my issue.
I am developing a website on VisualStudio using VB. In one section of my site I make a DataBase Query, store the result in a DataTable and display it. I give the user the option of dowloading the information, what I would like to do is to download an XLS file to the client's side with the information in the datatable without creating the xls on the server side.
I currently have the following code section to send the file to the user
Dim fileToDownload = Server.MapPath("~/docs/QuejometroVF.pdf")
Response.ContentType = "application/octet-stream"
Dim cd = New ContentDisposition()
cd.Inline = False
cd.FileName = Path.GetFileName(fileToDownload)
Response.AppendHeader("Content-Disposition", cd.ToString())
Dim fileData = System.IO.File.ReadAllBytes(fileToDownload)
Response.OutputStream.Write(fileData, 0, fileData.Length)
But it requires a path to a local file in order to send it.
First I would like to know how to create a xls file from the datatable (only in memory) and then send that object as a file to the client's computer. If it is not possible, Could you tell me how to write the xls file in my server so I can then send it using the code above? I have not really figured out how to do it yet.
I was thinking on doint it that way because I don't want to keep files in the server when I already have that information on the database and I don't pretend on keeping that file stored.
Thank you
I export data to xls file using the following code, my backend is an Oracle database and that's where I get the data:
Dim MyConnection As OracleConnection = OpenConnection(Session("USERNAME"), Session("PASSWORD"))
Dim MyDataSet As New DataSet
MyDataSet = GetExportData(MyConnection, Session("UserDataKey"), Session("CompoundKey"), Session("LastOfCompoundKey"))
'I rename the dataset's table columns to what I want in the xls file
MyDataSet.Tables!data.Columns(0).ColumnName = "IDNumber"
MyDataSet.Tables!data.Columns(1).ColumnName = "FirstName"
MyDataSet.Tables!data.Columns(2).ColumnName = "LastName"
MyDataSet.Tables!data.Columns(3).ColumnName = "Address"
MyDataSet.Tables!data.Columns(4).ColumnName = "City"
MyDataSet.Tables!data.Columns(5).ColumnName = "State"
MyDataSet.Tables!data.Columns(6).ColumnName = "ZipCode"
MyDataSet.Tables!data.Columns(7).ColumnName = "Phone_Area"
MyDataSet.Tables!data.Columns(8).ColumnName = "Phone_Prefix"
MyDataSet.Tables!data.Columns(9).ColumnName = "Phone_Suffix"
MyDataSet.Tables!data.Columns(10).ColumnName = "Email"
MyDataSet.Tables!data.Columns(11).ColumnName = "BirthDay"
Response.ClearContent()
'I create the filename I want the data to be saved to and set up the response
Response.AddHeader("content-disposition", "attachment; filename=" & Replace(Session("Key0"), " ", "-") & "-" & Session("Key1") & "-" & Replace(Replace(Trim(Session("Key2")), ".", ""), " ", "-") & ".xls")
Response.ContentType = "application/excel"
Response.Charset = ""
EnableViewState = False
Dim tw As New System.IO.StringWriter
Dim hw As New System.Web.UI.HtmlTextWriter(tw)
'Create and bind table to a datagrid
Dim dgTableForExport As New DataGrid
If MyDataSet.Tables.Count > 0 Then
If MyDataSet.Tables(0).Rows.Count > 0 Then
dgTableForExport.DataSource = MyDataSet.Tables(0) ' .DefaultView
dgTableForExport.DataBind()
'Finish building response
Dim strStyle As String = "<style>.text { mso-number-format:\#; } </style>"
For intTemp As Integer = 0 To MyDataSet.Tables(0).Rows.Count - 1
For intTemp2 As Integer = 0 To MyDataSet.Tables(0).Columns.Count - 1
dgTableForExport.Items(intTemp).Cells(intTemp2).Attributes.Add("class", "text")
Next
Next
End If
End If
dgTableForExport.RenderControl(hw)
Response.Write(style)
' Write the HTML back to the browser.
Response.Write(tw.ToString())
Response.End()
'Close, clear and dispose
MyConnection.Close()
MyConnection.Dispose()
MyConnection = Nothing
I copied and pasted this from one of my projects, it's untested and may contain error but should get you started.
You can use a MemoryStream or to write the file to Response stream using Response.Write method.
Creating an excel file from a data table is fairly easy as you can just create a GridView and bind the table to it.
Here is a code snippet that does what you need.
Public Sub DownloadExcel(outputTable as System.Data.DataTable)
Dim gv As New GridView
Dim tw As New StringWriter
Dim hw As New HtmlTextWriter(tw)
Dim sheetName As String = "OutputFilenameHere"
gv.DataSource = outputTable
gv.DataBind()
gv.RenderControl(hw)
Response.AddHeader("content-disposition", "attachment; filename=" & sheetName & ".xls")
Response.ContentType = "application/octet-stream"
Response.Charset = ""
EnableViewState = False
Response.Write(tw.ToString)
Response.End()
End Sub
There are a few issues with this method:
This doesn't output a native excel file. Instead, it outputs the HTML for a GridView that Excel will detect and notify the user that the content doesn't match the extension. However, it WILL display in Excel correctly if the user selects 'Yes' from the dialog box.
Earlier versions of Firefox and Chrome didn't like this method and instead download the file with a .html extension. I just tested it in both browsers and it worked with the most up to date versions.
Ideally, you should probably use Excel on your webserver to create native spreadsheets, but this will work if you (like me) don't have the means to do so.
I'm trying to insert data into Oradores Table in Access using Visual Basic. The code I have is:
'Public Variables
novo_nome_comum = TxtNComum.Text
novo_nome_completo = TxtNCompleto.Text
nova_morada = TxtMorada.Text
nova_localidade = TxtLocalidade.Text
novo_codpostal = TxtCPostal.Text
novo_tel1 = TxtTel1.Text
novo_tel2 = TxtTel2.Text
novo_tlm1 = TxtTlm1.Text
novo_tlm2 = TxtTlm2.Text
novo_email1 = TxtMail1.Text
novo_email2 = TxtMail2.Text
nova_cong = TxtCong.Text
'End of Public Variables
Dim connect As New OleDbConnection("Provider=Microsoft.ACE.OleDb.12.0;" & "Data Source =C:\Users\Fernando\Documents\Visual Studio 2012\Projects\Agenda_DP\Agenda_DP\AgendaDP.accdb")
connect.Open()
Dim cmd As OleDbCommand = connect.CreateCommand()
cmd.CommandText = "INSERT INTO Oradores (NomeComum, NomeCompleto, Morada, Localidade, CodPostal, Telefone, Telefone2, Telemovel, Telemovel2, email, email2, Congregacao) VALUES('novo_nome_comum', 'novo_nome_completo', 'nova_morada', 'nova_localidade', 'novo_codpostal', 'novo_tel1', 'novo_tel2','novo_tlm1', 'novo_tlm2', 'novo_email1', 'novo_email2', 'nova_cong')"
cmd.ExecuteNonQuery()
connect.Close()
However, this is not working, and I don't understand why.
I searched in MSDN and I'm copying the example quoted to my code.
Is there anyone who could give me an hand?
Thanks in advance.
Fernando Pessoa
I will share you a piece of code:
Try
Dim con As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=yourDB.accdb;")
Dim cb As String = "insert into Table1 (Date1, Sample1) VALUES (#p1, #p2)"
Dim cmd As New System.Data.OleDb.OleDbCommand
cmd.Connection = con
cmd.CommandText = cb
cmd.Parameters.AddWithValue("#p1", Me.DateTimePicker1.Value.ToShortDateString())
cmd.Parameters.AddWithValue("#p2", Me.TextBox1.Text)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
Catch ex As Exception
MessageBox.Show(Err.Description)
End Try
It is working fine in my sample.
You can visit a post called MS Access - VB .net - connect and operate
I am trying to create named ranges in Excel with OpenXML. I am able to add a DefinedName in the DefinedNames collection, but that does not seem to do anything. I noticed a place in the ExtendedFileProperties where the names of ranges are being saved, a structure called "TitlesOfParts". I have tried adding an entry in there but that causes excel to throw an error and the named range is not created. Here is the code I am using:
public void AddNamedRange(string pNamedRangeRef, string pNamedRangeName)
{
DefinedName _definedName = new DefinedName() { Name = pNamedRangeName, Text = pNamedRangeRef };
_workbook.Descendants<DocumentFormat.OpenXml.Spreadsheet.DefinedNames>().First().Append(_definedName);
DocumentFormat.OpenXml.VariantTypes.VTLPSTR _t = new DocumentFormat.OpenXml.VariantTypes.VTLPSTR() { Text = pNamedRangeName };
_spreadsheet.ExtendedFilePropertiesPart.Properties.TitlesOfParts.VTVector.Append(_t);
_spreadsheet.ExtendedFilePropertiesPart.Properties.TitlesOfParts.VTVector.Size++;
}
Using the Open XML SDK 2.0 Productivity Tool for Microsoft Office, to define a global/workbook-wide named range is pretty easy:
DefinedNames definedNamesCol = new DefinedNames(); //Create the collection
DefinedName definedName = new DefinedName()
{ Name = "test", Text="Sheet1!$B$2:$B$4" }; // Create a new range
definedNamesCol.Append(definedName); // Add it to the collection
workbook.Append(definedNamesCol); // Add collection to the workbook
The below code did the trick for me. After this I was able to see the name ranges in excel also.
var wbPart = document.WorkbookPart;
Workbook workbook = wbPart.Workbook;
DefinedName definedName1 = new DefinedName { Name = "ColumnRange",Text = "Sheet1!$A$1:$I$1"};
DefinedName definedName2 = new DefinedName { Name = "RowRange", Text = "Sheet1!$A$1:$A$15"};
if (workbook.DefinedNames == null)
{
DefinedNames definedNames1 = new DefinedNames();
definedNames1.Append(definedName1);
definedNames1.Append(definedName2);
workbook.DefinedNames = definedNames1;
}
'vb.net
Imports DocumentFormat.OpenXml
Imports DocumentFormat.OpenXml.Packaging
Imports DocumentFormat.OpenXml.Spreadsheet
Dim WB As SpreadsheetDocument = SpreadsheetDocument.Create("C:\NewFile.xmlx", SpreadsheetDocumentType.Workbook)
Dim WBP As WorkbookPart = WB.AddWorkbookPart
Dim dn As DefinedName = New DefinedName()
dn.Name = "test"
dn.Text = "XFW_PLP_CalcPlan!A5:$I$1"
Dim dns As DefinedNames = New DefinedNames()
dns.Append(dn)
WBP.Workbook.Append(dns)