Is it possible to generate .xlsb excel file format using NPOI in C#? - npoi

We tried with the below code and cannot able to open in Microsoft Excel. Is this the right way to generate the .xlsb file using NPOI? Please advise
using (var exportdata = new MemoryStream())
{
var name = output.xlsb;
System.Web.HttpContext.Current.Response.Clear();
workbook.Write(exportdata);
System.Web.HttpContext.Current.Response.ContentType = "application / vnd.ms - excel.sheet.binary.macroEnabled.12";
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename=" + name + ";"));
System.Web.HttpContext.Current.Response.BinaryWrite(exportdata.ToArray());
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.End();
}

Related

How to create workbook in Jmeter using JSR223 or beanshell sampler?

I'm getting error when trying to create a workbook in the Jmeter.
I'm using "tika-app.jar"
After workbook creation is done I want to write data in excel xlx file.
Below is my JSR223 sampler:
Error response which I'm getting is as below:
Can someone help
Copy tika-app-xxx.jar to "lib" folder of your JMeter installation
Restart JMeter to pick the .jar up
Switch to groovy language
Your code should start working without "Class not found" errors
If you're looking for "recipes" with regards to how to fill the Excel file check out Busy Developers' Guide to HSSF and XSSF Features
Just in case a piece of code from the above guide:
Workbook wb = new HSSFWorkbook();
//Workbook wb = new XSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");
// Create a row and put some cells in it. Rows are 0 based.
Row row = sheet.createRow(0);
// Create a cell and put a value in it.
Cell cell = row.createCell(0);
cell.setCellValue(1);
// Or do it on one line.
row.createCell(1).setCellValue(1.2);
row.createCell(2).setCellValue(
createHelper.createRichTextString("This is a string"));
row.createCell(3).setCellValue(true);
// Write the output to a file
try (OutputStream fileOut = new FileOutputStream("workbook.xls")) {
wb.write(fileOut);
}

reading data from multiple tabs in excel

I have some data in multiple tabs in excel and those need to be read using cypress. Is there a way to do it? The only suggested way to read data from excel is to convert to JSON file. So, I referred and wrote this in ./cypress/support/command.js file with an intention that each tab will be stored as JSON file.
Cypress.Commands.add('dataFile', (excelFile) => {
let XLSX = require('xlsx');
let fs = require('fs');
let XLBook = XLSX.readFile('cypress/fixtures/' + excelFile);
let XLTabs = XLBook.SheetName;
for(let i = 0; i < XLTabs.length; i++)
{
let XLTabName = XLTabs[i].toString();
let XLData = XLSX.utils.sheet_to_json(XLBook.Sheets[XLTabs[i]);
fs.writeFile('./cypress/fixtures/jSONData.json', JSON.stringify(XLData , null, 2), (e: string) => {
if(e) {
console.log(e);
}
});
}
});
I used the below command in my test to use it.
cy.dataFile('File1.xlsx');
But, the test was highlighting this error:
Property 'dataFile' does not exist on type 'cy & EventEmitter'.ts(2339)
Please read Types for custom commands to resolve the error
Property 'dataFile' does not exist on type 'cy & EventEmitter'.ts(2339)
But you cannot use a custom command, because both let XLSX = require('xlsx') and let fs = require('fs') must be used in a task.
Please see this answer Read excel files in Cypress for the broad strokes.

UpdateListItems method from SharePoint Lists Web Service fails with a Soap Server Exception

I'm developing a MS Office 2010 Excel AddIn from a client machine which doesn't have SharePoint installed in it. I imported a Lists web service reference from a remote SharePoint server. I developed a wpf user control which can load data from the list and show it in the excel worksheet. It works perfectly. Then I extend my client application to update list items in the server. So I tried to update list items in the server with UpdateListItems method using the web service reference.
But it failed with an exception "Soap Server Exception.". I can't figure out what's wrong here as I can import data without any problem. Following is my code block.
SPListsWS.Lists myListUpdateProxy = new SPListsWS.Lists();
myListUpdateProxy.Credentials = CredentialCache.DefaultCredentials;
myListUpdateProxy.Url = "http://uvo1y1focm66gonf7gw.env.cloudshare.com/_vti_bin/Lists.asmx";
XmlNode listView = myListUpdateProxy.GetListAndView("Products", "");
string listID = listView.ChildNodes[0].Attributes["Name"].Value;
string viewID = listView.ChildNodes[1].Attributes["Name"].Value;
XmlDocument Xdoc = new XmlDocument();
XmlElement updateElement = Xdoc.CreateElement("updateElement");
updateElement.SetAttribute("OnError", "Continue");
updateElement.SetAttribute("ListVersion", "1");
updateElement.SetAttribute("ViewName", viewID);
updateElement.InnerXml = "<Method ID='1' Cmd='Update'>"
+ "<Field Name = 'ID'>" + index + "</Field>"
+ "<Field Name = 'Title'>" + prodTitle + "</Field>"
+ "<Field Name = 'Product_SKU'>" + prodSKU + "</Field>"
+ "<Field Name = 'Product_Price'>" + prodPrice + "</Field>"
+ "</Method>";
XmlNode responseXml = myListUpdateProxy.UpdateListItems("Products", updateElement);
MessageBox.Show(responseXml.OuterXml);
To update items you should use UpdateListItems instead of GetListItems. Also, when using UpdateListItems, wrap your <Metdod> tags in <Batch> elements. This would be in place of your updateElement. See if that works, and, if not, please include the responseText of the actual error message along with what version of SharePoint you are using.

Invoke source control compare operation in vs2012 extension

I am writing a vs2012 extension that will talk to TFS 2010 (though I would prefer if it could also work with tfs2012).
I need to invoke a compare operations on a file from the extension.
I want to use the default compare tool that is configured in visual studio at the moment of the innovation (because the user can configure a different compare tool).
I have the location of the file and I want to be able to invoke the following:
open the default compare.
open a compare with latest version
open a compare with workspace version
Use IVsDifferenceService to invoke Visual Studio diff tool from your VSPackage:
private void Compare(string leftFile, string rightFile)
{
var diffService = (IVsDifferenceService)GetService(typeof(SVsDifferenceService));
if (diffService != null)
{
ErrorHandler.ThrowOnFailure(
diffService.OpenComparisonWindow(leftFile, rightFile).Show()
);
}
}
To test it you need to set the workspace and download the file you want to compare:
// TODO: add some error handling
var tpc = new TfsTeamProjectCollection(new Uri("http://tfs.company.com:8080/tfs"));
var vcs = tpc.GetService<VersionControlServer>();
var workspace = vcs.GetWorkspace(Environment.MachineName, vcs.AuthorizedUser);
string localItem = #"C:\workspace\project\somefile.cs";
var folder = workspace.GetWorkingFolderForLocalItem(localItem);
var item = vcs.GetItem(folder.ServerItem, VersionSpec.Latest);
var latestItem = string.Format("{0}~{1}", localItem, item.ChangesetId);
item.DownloadFile(latestItem);
Compare(localItem, latestItem);
References:
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;

Save all files in Visual Studio project as UTF-8

I wonder if it's possible to save all files in a Visual Studio 2008 project into a specific character encoding. I got a solution with mixed encodings and I want to make them all the same (UTF-8 with signature).
I know how to save single files, but how about all files in a project?
Since you're already in Visual Studio, why not just simply write the code?
foreach (var f in new DirectoryInfo(#"...").GetFiles("*.cs", SearchOption.AllDirectories)) {
string s = File.ReadAllText(f.FullName);
File.WriteAllText (f.FullName, s, Encoding.UTF8);
}
Only three lines of code! I'm sure you can write this in less than a minute :-)
This may be of some help.
link removed due to original reference being defaced by spam site.
Short version: edit one file, select File -> Advanced Save Options. Instead of changing UTF-8 to Ascii, change it to UTF-8. Edit: Make sure you select the option that says no byte-order-marker (BOM)
Set code page & hit ok. It seems to persist just past the current file.
In case you need to do this in PowerShell, here is my little move:
Function Write-Utf8([string] $path, [string] $filter='*.*')
{
[IO.SearchOption] $option = [IO.SearchOption]::AllDirectories;
[String[]] $files = [IO.Directory]::GetFiles((Get-Item $path).FullName, $filter, $option);
foreach($file in $files)
{
"Writing $file...";
[String]$s = [IO.File]::ReadAllText($file);
[IO.File]::WriteAllText($file, $s, [Text.Encoding]::UTF8);
}
}
I would convert the files programmatically (outside VS), e.g. using a Python script:
import glob, codecs
for f in glob.glob("*.py"):
data = open("f", "rb").read()
if data.startswith(codecs.BOM_UTF8):
# Already UTF-8
continue
# else assume ANSI code page
data = data.decode("mbcs")
data = codecs.BOM_UTF8 + data.encode("utf-8")
open("f", "wb").write(data)
This assumes all files not in "UTF-8 with signature" are in the ANSI code page - this is the same what VS 2008 apparently also assumes. If you know that some files have yet different encodings, you would have to specify what these encodings are.
Using C#:
1) Create a new ConsoleApplication, then install Mozilla Universal Charset Detector
2) Run code:
static void Main(string[] args)
{
const string targetEncoding = "utf-8";
foreach (var f in new DirectoryInfo(#"<your project's path>").GetFiles("*.cs", SearchOption.AllDirectories))
{
var fileEnc = GetEncoding(f.FullName);
if (fileEnc != null && !string.Equals(fileEnc, targetEncoding, StringComparison.OrdinalIgnoreCase))
{
var str = File.ReadAllText(f.FullName, Encoding.GetEncoding(fileEnc));
File.WriteAllText(f.FullName, str, Encoding.GetEncoding(targetEncoding));
}
}
Console.WriteLine("Done.");
Console.ReadKey();
}
private static string GetEncoding(string filename)
{
using (var fs = File.OpenRead(filename))
{
var cdet = new Ude.CharsetDetector();
cdet.Feed(fs);
cdet.DataEnd();
if (cdet.Charset != null)
Console.WriteLine("Charset: {0}, confidence: {1} : " + filename, cdet.Charset, cdet.Confidence);
else
Console.WriteLine("Detection failed: " + filename);
return cdet.Charset;
}
}
I have created a function to change encoding files written in asp.net.
I searched a lot. And I also used some ideas and codes from this page. Thank you.
And here is the function.
Function ChangeFileEncoding(pPathFolder As String, pExtension As String, pDirOption As IO.SearchOption) As Integer
Dim Counter As Integer
Dim s As String
Dim reader As IO.StreamReader
Dim gEnc As Text.Encoding
Dim direc As IO.DirectoryInfo = New IO.DirectoryInfo(pPathFolder)
For Each fi As IO.FileInfo In direc.GetFiles(pExtension, pDirOption)
s = ""
reader = New IO.StreamReader(fi.FullName, Text.Encoding.Default, True)
s = reader.ReadToEnd
gEnc = reader.CurrentEncoding
reader.Close()
If (gEnc.EncodingName <> Text.Encoding.UTF8.EncodingName) Then
s = IO.File.ReadAllText(fi.FullName, gEnc)
IO.File.WriteAllText(fi.FullName, s, System.Text.Encoding.UTF8)
Counter += 1
Response.Write("<br>Saved #" & Counter & ": " & fi.FullName & " - <i>Encoding was: " & gEnc.EncodingName & "</i>")
End If
Next
Return Counter
End Function
It can placed in .aspx file and then called like:
ChangeFileEncoding("C:\temp\test", "*.ascx", IO.SearchOption.TopDirectoryOnly)
if you are using TFS with VS :
http://msdn.microsoft.com/en-us/library/1yft8zkw(v=vs.100).aspx
Example :
tf checkout -r -type:utf-8 src/*.aspx
Thanks for your solutions, this code has worked for me :
Dim s As String = ""
Dim direc As DirectoryInfo = New DirectoryInfo("Your Directory path")
For Each fi As FileInfo In direc.GetFiles("*.vb", SearchOption.AllDirectories)
s = File.ReadAllText(fi.FullName, System.Text.Encoding.Default)
File.WriteAllText(fi.FullName, s, System.Text.Encoding.Unicode)
Next
If you want to avoid this type of error :
Use this following code :
foreach (var f in new DirectoryInfo(#"....").GetFiles("*.cs", SearchOption.AllDirectories))
{
string s = File.ReadAllText(f.FullName, Encoding.GetEncoding(1252));
File.WriteAllText(f.FullName, s, Encoding.UTF8);
}
Encoding number 1252 is the default Windows encoding used by Visual Studio to save your files.
Convert from UTF-8-BOM to UTF-8
Building on rasx's answer, here is a PowerShell function that assumes your current files are already encoded in UTF-8 (but maybe with BOM) and converts them to UTF-8 without BOM, therefore preserving existing Unicode characters.
Function Write-Utf8([string] $path, [string] $filter='*')
{
[IO.SearchOption] $option = [IO.SearchOption]::AllDirectories;
[String[]] $files = [IO.Directory]::GetFiles((Get-Item $path).FullName, $filter, $option);
foreach($file in $files)
{
"Writing $file...";
[String]$s = [IO.File]::ReadAllText($file, [Text.Encoding]::UTF8);
[Text.Encoding]$e = New-Object -TypeName Text.UTF8Encoding -ArgumentList ($false);
[IO.File]::WriteAllText($file, $s, $e);
}
}
Experienced encoding problems after converting solution from VS2008 to VS2015. After conversion all project files was encoded in ANSI, but they contained UTF8 content and was recongnized as ANSI files in VS2015. Tried many conversion tactics, but worked only this solution.
Encoding encoding = Encoding.Default;
String original = String.Empty;
foreach (var f in new DirectoryInfo(path).GetFiles("*.cs", SearchOption.AllDirectories))
{
using (StreamReader sr = new StreamReader(f.FullName, Encoding.Default))
{
original = sr.ReadToEnd();
encoding = sr.CurrentEncoding;
sr.Close();
}
if (encoding == Encoding.UTF8)
continue;
byte[] encBytes = encoding.GetBytes(original);
byte[] utf8Bytes = Encoding.Convert(encoding, Encoding.UTF8, encBytes);
var utf8Text = Encoding.UTF8.GetString(utf8Bytes);
File.WriteAllText(f.FullName, utf8Text, Encoding.UTF8);
}
the item is removed from the menu in Visual Studio 2017
You can still access the functionality through File-> Save As -> then clicking the down arrow on the Save button and clicking "Save With Encoding...".
You can also add it back to the File menu through Tools->Customize->Commands if you want to.
I'm only offering this suggestion in case there's no way to automatically do this in Visual Studio (I'm not even sure this would work):
Create a class in your project named 足の不自由なハッキング (or some other unicode text that will force Visual Studio to encode as UTF-8).
Add "using MyProject.足の不自由なハッキング;" to the top of each file. You should be able to do it on everything by doing a global replace of "using System.Text;" with "using System.Text;using MyProject.足の不自由なハッキング;".
Save everything. You may get a long string of "Do you want to save X.cs using UTF-8?" messages or something.

Resources