I am trying to export JqGrid to excel so i follow this instruction and i use it like at below.
var grid = new JqGridModelParticipiant().JqGridParticipiant;
var query = db.ReservationSet.Select(r => new
{
r.Id,
Name = r.Doctor.Name,
Identity = r.Doctor.Identity,
Title = r.Doctor.Title.Name,
Total = r.TotalTL,
Organization = r.Organization.Name
});
grid.ExportToExcel(query,"file.xls");
And i get below exception on the line of " grid.ExportToExcel(query,"file.xls");"
Data binding directly to a store query (DbSet, DbQuery, DbSqlQuery) is
not supported. Instead populate a DbSet with data, for example by
calling Load on the DbSet, and then bind to local data. For WPF bind
to DbSet.Local. For WinForms bind to DbSet.Local.ToBindingList().
As far as i understand that it expect to have ObservableCollection that is on DbSet.Local member. But i am working on projected query so i can't do that.
What is the solution for this problem.
In the answer I posted the demo which shows how to implement export to Excel (real *.XLSX file instead of HTML fragment renamed to *.XLS used here).
The method used for exported to the Excel in jqSuite (the demo) produce HTML fragment like
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: application/excel; charset=utf-8
Server: Microsoft-IIS/7.0
X-AspNetMvc-Version: 2.0
content-disposition: attachment; filename=grid.xls
X-AspNet-Version: 2.0.50727
X-Powered-By: ASP.NET
Date: Fri, 29 Jun 2012 14:24:54 GMT
Connection: close
<table cellspacing="0" rules="all" border="1" id="_exportGrid" style="border-collapse:collapse;">
<tr>
<td>OrderID</td><td>CustomerID</td><td>OrderDate</td><td>Freight</td><td>ShipName</td>
</tr><tr>
<td>10248</td><td>VINET</td><td>1996/07/04</td><td>32.3800</td><td>Vins et alcools Chevalier</td>
</tr><tr>
<td>10249</td><td>TOMSP</td><td>1996/07/05</td><td>11.6100</td><td>Toms Spezialitäten</td>
</tr><tr>
<td>10250</td><td>HANAR</td><td>1996/07/08</td><td>65.8300</td><td>Hanari Carnes</td>
</tr><tr>
...
</table>
instead of creating of real Excel file. The way is very unsafe because at the opening the "Standard" type of data will be always used. For example if you would export the data like
<td>10249</td><td>TOMSP</td><td>1996/07/05</td><td>11.02.12</td><td>Toms Spezialitäten</td>
the text "11.02.12" will be automatically converted to the date 11.02.2012 if German locale are used as default:
The name "Toms Spezialitäten" from will be wrong displayed as "Toms Spezialitäten".
It can be especially dangerous in case of large table where some small part of data in the middle of grid will be wrong converted. In one project I displayed information about Software and some software versions will be wrong converted to the Date type.
Because of such and other close problems I create real Excel file on the server using Open XML SDK 2.5 or Open XML SDK 2.0. In the way one have no problems described above. So I recommend you to follow the approach described in my old answer.
Related
Using PHPSpreadsheet saving XLSX format works OK running the default code
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
$writer->save("filename.xlsx");
But if I want to have the user to select the target directory using
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="filename.xlsx"');
header('Cache-Control: max-age=0');
$writer = IOFactory::createWriter($spreadSheet, 'Xlsx');
$writer->save('php://output');
The file saves OK but Excel 2016 does not want to open it. Excel returns the following error
Excel Error
I looked through all documentation and posts but cannot find the solution.
Thanks !
Edit: Just in case, this solution does not work for me.
Edit 2: The sample provided Simple Download Xlsx works perfectly, but when doing a copy/paste for my spreadsheet, Chrome gives me a
Resource interpreted as Document but transferred with MIME type application/octet-stream
Edit 3: Used
ob_end_flush(); to clean any left over header in my code.
The file now saves OK, but needs repair when opening in Excel. Why ?
Thanks
Solution:
Bug from PhpSpreadsheet.
When using
header("Content-Type: application/vnd.ms-excel");
i.e. compatibility mode for Excel, the file opens OK.
I've been puzzling on this on and off for months and can't find a solution.
The MTA claims to provide historical data in form of daily dumps in GTFS format here:
[http://web.mta.info/developers/MTA-Subway-Time-historical-data.html][1]
See for yourself by downloading the example they provide, in this case Sep, 17th , 2014:
[https://datamine-history.s3.amazonaws.com/gtfs-2014-09-17-09-31][1]
My problem? The file is gobbledygook. It does not follow GTFS specifications, has no extension, and when I open it using a text editor it looks like 7800 lines of this:
n
^C1.0^X �枪�^Eʞ>`
^C1.0^R^K
^A1^R^F^P����^E^R^K
^A2^R^F^P����^E^R^K
^A3^R^F^P����^E^R^K
^A4^R^F^P����^E^R^K
^A5^R^F^P����^E^R^K
^A6^R^F^P����^E^R^K
^AS^R^F^P����^E^R[
^F000001^ZQ
6
^N050400_1..S02R^Z^H20140917*^A1�>^V
^P01 0824 242/SFY^P^A^X^C^R^W^R^F^Pɚ��^E"^D140Sʚ>^F
^AA^R^AA^RR
^F000002"H
6
Per the MTA site (appears untrue)
All data is formatted in GTFS-realtime
Any idea on the steps necessary to transform this mystery file into usable GTFS data? Is there some encoding I am missing? I have looked for 10+ and been unable to come up with a solution.
Also, not to be a stickler but I am NOT referring to the MTA's realtime data feed, which is correctly formatted and usable. I am specifically referring to the historical data dumps I reference above (have received many "solutions" referring only to realtime data feed)
The file you link to is in GTFS-realtime format, not GTFS, and the page you linked to does a very bad job of explaining which format their data is actually in (though it is mentioned in your quote).
GTFS is used to store schedule data, like routes and scheduled arrival times.
GTFS-realtime is generally used to transfer actual transit performance data in real-time, like vehicle locations and expected or actual arrival times. It is a protobuf, a specification for compiled binary data publicized by Google, which means you can't usefully read it in a text editor, but you instead have to load it programmatically using the Google protobuf tools. It can be used as a historical data format in the way MTA is here, by making daily dumps of the GTFS-rt feed publicly available. It's called GTFS-realtime because various data fields in the realtime like route_id, trip_id, and stop_id are designed to link to the published GTFS schedules.
I confirmed the validity of the data you linked to by decompiling it using the gtfs-realtime.proto specification and the Google protobuf tools for Python. It begins:
header {
gtfs_realtime_version: "1.0"
timestamp: 1410960621
}
entity {
id: "000001"
trip_update {
trip {
trip_id: "050400_1..S02R"
start_date: "20140917"
route_id: "1"
}
stop_time_update {
arrival {
time: 1410960713
}
stop_id: "140S"
}
}
}
...
and continues in that vein for a total of 55833 lines (in the default string output format).
EDIT: the Python script used to convert the protobuf into string representation is very simple:
import gtfs_realtime_pb2 as gtfs_rt
f = open('gtfs-rt.pb', 'rb')
raw_str = f.read()
msg = gtfs_rt.FeedMessage()
msg.ParseFromString(raw_str)
print msg
This requires gtfs-realtime.proto to have been compiled into gtfs_realtime_pb2.py using protoc (following the instructions in the Python protobuf documentation under "Compiling Your Protocol Buffers") and placed in the same directory as the Python script. Furthermore, the binary protobuf downloaded from the MTA needs to be named gtfs-rt.pb and located in the same directory as the Python script.
I'm trying to use the iCalendar gem to import some iCal files on a rails 4 site.
Sometimes the file is of type 'text/calendar;charset=utf-8' and sometimes its 'text/calendar; charset=UTF-8;'
I am retrieving it like this:
uri = URI.parse(url)
calendar = Net::HTTP.get_response(uri)
new_calendar = Icalendar.parse(calendar.body)
When its text/calendar;charset=utf-8 it works fine. but when its text/calendar; charset=UTF-8 encoded I get UTF codes in the string
SUMMARY:Tech Job Fair – City(ST) – Jul 1, 2015
ends up being
["Tech Job Fair \xE2\x80\x93 City(ST) \xE2\x80\x93 Jul 1", " 2015"]
Which is then saved to the database and that is undesirable.
Is the charset/content-type revealing the problem here or could it actually just be encoded wrong from the source?
How do I change my retrieval commands to strip those codes out effectively or tell it its a UTF string so it doesn't include them in the first place?
Update: it looks like some are text/calendar;charset=utf-8 and some are text/calendar;charset=UTF-8 and some are text/calendar; charset=UTF-8. Note the last one has a space between the two segments. Could this be causing an issue?
Update2: Opening up my three example iCal files in Notepad++ shows them encoded as "UTF-8 without BOM" in the menu.
I am using Primefaces 3.1.1 charts in my application, there is no problem generating charts in JSF page, but I'm trying to find out if it's possible to generate image (png or jpeg) for the charts so that I can insert these images into an Excel file (Apache POI) in java.
I know the latest Primefaces version 3.4.1 has an Export Chart feature, but the generated image only occurs at the client side (it's jqPlot). But I need it on the server side.
Currently we are using jFreeChart in the backing bean for this purpose, so the charts in browser looked very different from the charts in Excel. We are trying to find out whether by upgrading to Primefaces 3.4.1 can give us the option to make the charts in browser and the charts in Excel looked the same? Or is there another way of doing this?
Using mojarra-2.1.3-FCS if this is a concern.
As in the accepted answer provided by Daniel, Primefaces' charts are not available at the server side. I add an answer here only to show a possible workaround.
At the client side, we assign the base64 PNG encoded string to a hidden field value, an example modified from Primefaces demo source code for export charts:
<h:form id="hform">
<p:lineChart value="#{testBean.linearModel}" legendPosition="e"
zoom="true" title="Linear Chart" minY="0" maxY="10"
style="width:500px;height:300px" widgetVar="chart" />
<p:commandButton id="exp" value="Export" icon="ui-icon-extlink"
onclick="exportChart();"
actionListener="#{testBean.submittedBase64Str}" />
<h:inputHidden id="b64" value="#{testBean.base64Str}" />
<script type="text/javascript">
function exportChart() {
// exportAsImage() will return a base64 png encoded string
img = chart.exportAsImage();
document.getElementById('hform:b64').value = img.src;
}
</script>
</h:form>
At the backing bean, we need to decode the string, a simple example as below:
public void submittedBase64Str(ActionEvent event){
// You probably want to have a more comprehensive check here.
// In this example I only use a simple check
if(base64Str.split(",").length > 1){
String encoded = base64Str.split(",")[1];
byte[] decoded = org.apache.commons.codec.binary.Base64.decodeBase64(encoded);
// Write to a .png file
try {
RenderedImage renderedImage = ImageIO.read(new ByteArrayInputStream(decoded));
ImageIO.write(renderedImage, "png", new File("C:\\out.png")); // use a proper path & file name here.
} catch (IOException e) {
e.printStackTrace();
}
}
}
The PNG file is now stored in the server, and you can continue to make use of that file in other parts of your codes.
As you already know Primefaces uses the jqPlot plugin to generate the charts , Since jqPlot is a jquery client side plugin it cannot generate anything on the server side , its a jquery plugin and not some server side api (jar)
So the answer is No :/
You might consider using some other server side chart generator (look at the links below) that will generate a better looking charts
13. Are there other "open source" chart libraries? (at the buttom)
What is the best open-source java charting library? (other than jfreechart)
I use ASP MVC3 framework, created an Excel file and outputted it using FileResult action with content type "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet".
When attempting to open it Excel just says "file is corrupt and cannot be opened."
When I open the source generated Excel file that was used to send the output it works without any problems. I also run file comparison on the bytes for both copies and the files are identical. I tried to email the corrupt file to myself and the attachment opens fine.
This leads me to believe it's a problem with headers or some sort of Excel/Windows security config.
If it is the latter, then I need a solution that won't make clients change their security settings.
EDIT - Found the setting:
I've found what setting causes this - "Enable protected view from files originated from the internet" in Excel's Trust Center / Protected View settings.
So I guess the question is - Is there a way for the file to appear trusted?
Here are the response headers:
Cache-Control:private
Content-Disposition:attachment;
filename="Report - Monday, March 19, 2012.xlsx" Content-Length:20569
Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
The action method that makes the output:
[HttpPost]
public virtual FileResult Export()
{
try
{
...
string newFilePath = createNewFile(...);
string downloadedFileName = "Report - " + DateTime.Now.ToString("D") + ".xlsx";
return File(newFilePath, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", downloadedFileName);
}
catch (Exception ex)
{
...
}
}
How I create the Excel file:
I have a template XLSX file witch column names and some pivot charts in other sheets. From C# I create a copy of this template and then call SQL Server which outputs data into 1st sheet using OLEDB connector:
set #SQL='insert into OPENROWSET(''Microsoft.ACE.OLEDB.12.0'', ''Excel 12.0;Database=' + #PreparedXLSXFilePath + ';'', ''SELECT * FROM [Data$]'') ...
Thanks in advance for any help.
You would need a digital signature in your Excel file. How to do this from code is another question.
More info here:
http://www.delphifaq.com/faq/windows_user/f2751.shtml