Paste data from clipboard to excel in right format - c#

In performance analyzer I copy data from table in clipboard.
And then paste it in excel file.
The result is:
But when I paste it in text editor, I simple looks like:
Function Name Inclusive Samples Exclusive Samples Inclusive Samples
% Exclusive Samples %
[clr.dll] 26 26 39.39 39.39
Bee.Client.Common.BeeRight.CheckRightsForBeeUser() 10 0 15.15 0.00
Bee.Client.Common.BeeRight.get_Invoke() 6 0 9.09 0.00
Bee.Client.Common.BeeRight.Method(string,string) 13 0 19.70 0.00
Bee.Client.Common.Custom.FmCustom..ctor() 9 0 13.64 0.00
So can you tell me, how can I archive this effect?
Thanks!
Update
I'll try to explain.
I have DataGridView in my winform application. I wrote some function, which copy data from table into clipboard (the result looks like the text in my example). If I paste this text from clipboard to excel, the result will be excel file with data from clipboard, but there will be no formatting at all and this excel will be hard to read.
I wonder, how they prepare data from table (pic 1) such a way, that when I paste it to excel, it has formatting (pic 2), and when I paste it in text editor, we saw raw text..

The cause, why the direct work between your datagrid and Excel is good, is the implementation of the DataGridView component and its reaction to Copy operation, and the behavior of the application, you want to paste the content into. It can use some special codes, which are ignored by Notepad.
EDIT
So, now I understand your interest pretty well. I don't know how it works in C#, but in Java it looks so.
Every time you have any information in the clipboard there are a lot of variants, how other applications can use this content.
Suppose I want to get the content from the clipboard. I do it so:
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable contents = clipboard.getContents(null);
but now I should determine how the information should look for my application, and here your question begins.
If I have a picture in the clipboard, I have only 1 possible representation of it:
[mimetype=image/x-java-image;representationclass=java.awt.Image]
If I have some text from Notepad, there are already 27 variants:
[mimetype=application/x-java-text-encoding;representationclass=[B]
[mimetype=application/x-java-serialized-object;representationclass=java.lang.String]
[mimetype=text/plain;representationclass=java.io.Reader]
[mimetype=text/plain;representationclass=java.lang.String]
[mimetype=text/plain;representationclass=java.nio.CharBuffer]
and so on...
If I have some cells from an Excel sheet, there are 56 variants:
[mimetype=application/x-java-text-encoding;representationclass=[B]
[mimetype=text/html;representationclass=java.io.Reader]
[mimetype=text/html;representationclass=java.lang.String]
[mimetype=text/html;representationclass=java.nio.CharBuffer]
[mimetype=text/html;representationclass=[C]
and so on...
there is even an Image-variant for Excel-cells!
[mimetype=image/x-java-image;representationclass=java.awt.Image]
That is why it is possible to copy some cells from Excel and paste them into Paint as bitmap! It is not possible for Notepad of course, because its developers did not want to work with this presentation.
Now we can see, the clipboard is not so primitive how it can seem to be. Each time an application can analyze the content and take the best variant of it.
Now you can try to find some infos for C# development. I'm sure, you'll get it!

Related

Microsoft Excel on save changes decimal point to 8

when i open on save excel the value displayed in excel is 596207726.09 but actual code behind value is 596207726.09000003.
why this change happaned?
But 596207726.09 in excel changed to 596207726.09000003 in code.
How 000003 getting added in code and how to solve the issue in c# code so it can take exact decimal point as given in Excel
For Example
596207726.09 - 596207726.09
596207726.092 - 596207726.092

Issue in using extremely huge Excel File with Formula in C#

In my current project, Aspose has been used to work with Excel file (XLXS). This excel file has 4 worksheets. First two sheets are empty except they have first row which contain column names. These tab got data through code and other two contains tons of complex formula based on these inputs. Just imagine first two tab as inputs, third tab as complex calculation and last tab as output. Average size of file ranges from 26MB to 48MB. Below piece of code does most of the work. After this method, the file has been saved in some physical location too. output date saved in DB. This process working fine so far with above range, but when size exceeded beyound 100MB, it started throwing Out of Memory exception. Hardly once or twice, it able to complete the process in around 80 - 100 mins.
public void CaclulateM(DataSet dataModel)
{
var workbook = this.ExcelModel.Workbook;
var ranges = ExcelModel.GetExcelModelRanges;
base.ImportInputsTo(workbook, ranges, dataModel);
workbook.CalculateFormula(false);
base.ExportOutputsTo(workbook, ranges, dataModel);
}
I tried out some of the solution provided by Aspose, but failed.I tried other dlls too including Interop, ExcelLibrary, NPOI, but same result.
https://forum.aspose.com/t/aspose-cell-dll-issue-for-xslb-file/164440
Please help or let me know if you need any other input to suggest anything. I cannot provide you the excel file due to confidentiality.

Reading Rich Text from Excel Range (cells) with Office Interop

(This question was formerly titled "C# / WPF : Going from Excel Interop "Range" to WPF "FlowDocument"" however I've made progress on that front that allows me to restrict my question. I'm leaving the original question below so existing answers will still make sense.)
I'm using Office Interop to read the contents of cells in an Excel worksheet. Some of those cells contain Rich Text (for example some words are italicized but not the whole cell) and I would like to capture them as RTF so I can then display them into WPF controls.
I have been able to obtain the RTF contents of cells using the clipboard API, where I use Excel Interop to copy a Range of one cell to the clipboard, and then read the clipboard, like so:
// Step 1 : retrieve the RTF from the clipboard as a string
string txt = Clipboard.GetText(TextDataFormat.Rtf);
// Step 2 : create a FlowDocument object and a TextRange object:
FlowDocument doc = new FlowDocument();
TextRange tr = new TextRange(doc.ContentStart, doc.ContentEnd);
// Step 3 : convert the clipboard string to a stream
byte[] byteArray = Encoding.ASCII.GetBytes(txt);
MemoryStream stream = new MemoryStream(byteArray);
// Step 4 : load that stream into TextRange
tr.Load(stream, DataFormats.Rtf);
If I then assign "doc" to the Document property of, say, a RichTextBox control, it'll display the content of the Excel cell with the exact same formatting as Excel does, down to colored words and font sizes.
However, this is extremely slow. It may take minutes to load a thousand cells that way, even if most are empty.
So here's my updated question : clearly Excel has a mechanism for returning the RTF content of an Excel cell, otherwise my Clipboard code couldn't work. But is there are more efficient way than the Clipboard to exploit that mechanism ? Ideally through Interop ?
Original question :
This may be an unusual question but as I'm quite new to C#, WPF and Interop, I might be going about things the wrong way so don't hesitate to offer a better approach. Here's what I'm trying to do :
I'm coding a WPF application that uses Office Interop to grab the contents of cells from an Excel worksheet. That content is text which may contain some formatting (for example some words are in bold, others are in italics). The application then displays that content in a "FlowDocumentScrollViewer" control on its GUI.
I want this "FlowDocumentScrollViewer" control to render the content from the Excel cell exactly as it appears in Excel, with formatting and everything.
The best I've managed so far is to display the cell's content without any formatting. Here's how this works : I use Office Interop to read a Range of cells from the worksheet and take their Value2 property. Value2 is of type "object". Then I create a FlowDocument object out of it, like so:
FlowDocument doc = new FlowDocument();
Paragraph p = new Paragraph(new Run(Variable_containing_a_Value2.ToString()));
doc.Blocks.Add(p);
And then I store this FlowDocument into the "FlowDocumentScrollViewer" Document property.
Now since I'm using "ToString()" on the Value2 I'm not surprised that any formatting information this object might contain disappears past this point.
My problem is, I haven't been able to find a way to create that FlowDocument, from that Value2 object, that preserves formatting.
Now, I know there has to be a way to get that information through, because when I copy my Excel cell and paste it in Word, for example, then the formatting is carried through. I just don't know how.
Help me Obiwans, you're my only hope, as even Google has failed me.
It seems to me that you have at least a couple of options that will work better than just copying the cell contents as text. The Range object has Copy() and CopyPicture() methods, which you can use to have Excel copy the contents of the range to the clipboard.
The basic Copy() method should (I haven't tested it) put the contents of the cell into the clipboard in a variety of formats, including RTF. And you should be able to get the RTF and put that into the FlowDocument element.
Using RTF, you may still not get exactly the representation as seen in Excel. The only way to do that is to have Excel do the rendering. In that case, you'll want the CopyPicture() method, which will put picture of the range on the clipboard. This will be either a bitmap or metafile, depending on the options you use for the method call. You can then retrieve these from the clipboard and put them into your FlowDocument.
Depending on what applications you're looking at, e.g. Word, there's yet another more complicated approach, one that I doubt would work with FlowDocument, but which they are using. That is, they are presenting the Excel range an OLE object. This is harder to implement, but has the advantage that it's a live representation of the original Excel document, and the user can edit the range in-place in the host application.
The above should be enough to get you pointed in the right direction, so at least you know what you're looking for when you do your web searches. As stated, your question is very broad, and so the above is necessarily vague as well. Once you've decided on a particular method, have done some research and made an attempt into implementing that method, if you still have problems you can post a new question, with a good Minimal, Complete, and Verifiable code example that shows clearly what you've tried, with a detailed explanation of what specifically you're still having trouble with.

Doxygen Wizard / MiKTeX C# Code Documentation Spacing & Table of Contents Issues

I am working on creating a PDF document of C# code. I am using the Doxygen GUI frontend and using the wizard to create LaTex files. Then, I take the generated refman.tex file and put it into TeXworks (part of MiKTeX) and generate the single pdf output. I can edit the .tex file to get rid of completely blank pages, change the page numbers, and more, but I am having two formatting issues I can't figure out.
The first problem is that each section is a "chapter" and the "chapter" headings are really far down the page (like probably ~40% down the page). I can't seem to find the setting in the .tex file that changes this. (See the linked screenshot below.)
The second problem has to do with the table of contents. It lists all the function names and their inputs. I don't want the inputs listed there. How do I change that?? (See the second screenshot below.)
Here is a small sample of the code...
%===== C O N T E N T S =====
\begin{document}
% Titlepage & ToC
\hypersetup{pageanchor=false,
bookmarksnumbered=true,
pdfencoding=unicode
}
\begin{titlepage}
\vspace*{7cm}
\begin{center}%
{\Large A\+PI Test \#1 \\[1ex]\large beta v1 }\\
\vspace*{1cm}
{\large DOXYGEN GENERATED}\\
\end{center}
\end{titlepage}
\let\cleardoublepage\clearpage
\clearemptydoublepage
\tableofcontents
\clearemptydoublepage
\pagenumbering{arabic}
\hypersetup{pageanchor=true}
%--- Begin generated contents ---
\chapter{Namespace Index}
\input{namespaces}
\chapter{Hierarchical Index}
\input{hierarchy}
\chapter{Class Index}
\input{annotated}
\chapter{File Index}
\input{files}
\chapter{Namespace Documentation}
I had the exact same problem! Using the package titlesec helped a lot. As titlesec accepts vertical values in the format field for the \titleformat command, so I used \vspace{-0.5in} to force the chapters up. I added the following code to my header.tex. JKust mind that I added this before the \usepackage[titles]{tocloft} line.
\usepackage{titlesec,titletoc}
% Headings 1
\titleformat{\chapter} % command
[display] % shape
{\vspace{-0.5in}\huge\bfseries\filcenter} % format
{\LARGE\thechapter} % label
{0.4ex} % Spacing between label and title
{} % before code

Paste from Excel into C# app, retaining full precision

I have data in an Excel spreadsheet with values like this:
0.69491375
0.31220394
The cells are formatted as Percentage, and set to display two decimal places. So they appear in Excel as:
69.49%
31.22%
I have a C# program that parses this data off the Clipboard.
var dataObj = Clipboard.GetDataObject();
var format = DataFormats.CommaSeparatedValue;
if (dataObj != null && dataObj.GetDataPresent(format))
{
var csvData = dataObj.GetData(format);
// do something
}
The problem is that csvData contains the display values from Excel, i.e. '69.49%' and '31.22%'. It does not contain the full precision of the extra decimal places.
I have tried using the various different DataFormats values, but the data only ever contains the display value from Excel, e.g.:
DataFormats.Dif
DataFormats.Rtf
DataFormats.UnicodeText
etc.
As a test, I installed LibreOffice Calc and copy/pasted the same cells from Excel into Calc. Calc retains the full precision of the raw data.
So clearly Excel puts this data somewhere that other programs can access. How can I access it from my C# application?
Edit - Next steps.
I've downloaded the LibreOffice Calc source code and will have a poke around to see if I can find out how they get the full context of the copied data from Excel.
I also did a GetFormats() call on the data object returned from the clipboard and got a list of 24 different data formats, some of which are not in the DataFormats enum. These include formats like Biff12, Biff8, Biff5, Format129 among other formats that are unfamiliar to me, so I'll investigate these and respond if I make any discoveries...
Also not a complete answer either, but some further insights into the problem:
When you copy a single Excel cell then what will end up in the clipboard is a complete Excel workbook which contains a single spreadsheet which in turn contains a single cell:
var dataObject = Clipboard.GetDataObject();
var mstream = (MemoryStream)dataObject.GetData("XML Spreadsheet");
// Note: For some reason we need to ignore the last byte otherwise
// an exception will occur...
mstream.SetLength(mstream.Length - 1);
var xml = XElement.Load(mstream);
Now, when you dump the content of the XElement to the console you can see that you indeed get a complete Excel Workbook. Also the "XML Spreadsheet" format contains the internal representation of the numbers stored in the cell. So I guess you could use Linq-To-Xml or similar to fetch the data you need:
XNamespace ssNs = "urn:schemas-microsoft-com:office:spreadsheet";
var numbers = xml.Descendants(ssNs + "Data").
Where(e => (string)e.Attribute(ssNs + "Type") == "Number").
Select(e => (double)e);
I've also tried to read the Biff formats using the Excel Data Reader however the resulting DataSets always came out empty...
The BIFF formats are an open specification by Microsoft. (Note, that I say specification not standard). Give a read to this to get an idea of what is going on.
Then those BIFF you see correspond to the some Excel formats. BIFF5 is XLS from Excel 5.0 and 95, BIFF8 is XLS from Excel 97 to 2003, BIFF12 is XLSB from Excel 2003, note that Excel 2007 can also produce them (I guess Excel 2010 too). There is some documentation here and also here (From OpenOffice) that may help you make sense of the binary there...
Anyways, there is some work has been done in past to parse this documents in C++, Java, VB and for your taste in C#. For example this BIFF12 Reader, the project NExcel, and ExcelLibrary to cite a few.
In particular NExcel will let you pass an stream which you can create from the clipboard data and then query NExcel to get the data. If you are going to take the source code then I think ExcelLibrary is much more readable.
You can get the stream like this:
var dataobject = System.Windows.Forms.Clipboard.GetDataObject();
var stream = (System.IO.Stream)dataobject.GetData(format);
And read form the stream with NExcel would be something like this:
var wb = getWorkbook(stream);
var sheet = wb.Sheets[0];
var somedata = sheet.getCell(0, 0).Contents;
I guess the actual Office libraries from Microsoft would work too.
I know this is not the whole tale, please share how is it going. Will try it if I get a chance.

Categories