Search Results

Search found 4783 results on 192 pages for 'excel vba'.

Page 41/192 | < Previous Page | 37 38 39 40 41 42 43 44 45 46 47 48  | Next Page >

  • Excel Circular Reference

    - by Demetre
    Simple question. I'm working in Excel 2007, and I want to convert 1000 grams into 1 kilogram when I input 1000g into a particular cell. So I decided to create the if statement below. However there is a problem with this. It's stating that it is a Circular Reference, and leaves me with a 0 value. Is there a simple way to fix this issue in excel? Here is the if statement I have. =IF(C8 >= 1000,CONVERT(C8,"g","k"),C8) Tell what you guys think. Thanks in advance.

    Read the article

  • Excel axis problem

    - by itid
    I am graphing the height above sea level obtained by GPS at 12 measuring stations, which are distributed along a straight line but NOT equidistantly. Excel does a nice job of creating a suitable Y axis. But, it insists on placing the 12 stations equidistantly along the X axis. Consequently, the line graph does not represent the true cross section of the terrain. It is only true at the stations themselves. Surely there must be a way that I can enter the actual distances between the stations into a column, and get Excel to read from that column and space the values accordingly? It is such a basic mapping procedure for geologists and many others. Thanks

    Read the article

  • Exporting from SSRS 2008 ReportViewer to Excel Causes Duplicate Columns

    - by Daniel Coffman
    I have a report that groups months by quarters, so each quarter has three months and the display of the months under the quarter is toggled by the quarter header. It looks just fine in the ReportViewer, but when exporting to Excel the first month in the quarter with data is duplicated and appended to the end of the quarter group. Here is what it looks like in the ReportViewer (with Quarters 2 and 4 expanded, note May and June do not have any data and show blank columns by design): http://i.imgur.com/MykZE.png This is how it looks when exported to Excel: http://i.imgur.com/zfLuk.png The collapsed Quarter should only show the LAST month in the quarter. You can see that in the Excel export July is inserted in Q1 even though it should be hidden entirely since that quarter is collapsed, December is appended to Q2, January is inserted into Q3, and April is duplicated and appended to Q4. Exporting the any format OTHER than Excel works correctly and does not insert these columns. A similar bug for rows was filed and marked as "by design": http://connect.microsoft.com/SQLServer/feedback/details/508823/reporting-services-2008-group-by-export-to-excel-duplicate-rows-csv-ok-pdf-ok How do I stop the export to Excel feature from inserting these duplicate columns?

    Read the article

  • Excel 2007 file writer in C# results in a corrupt file

    - by Martin
    Hi, I am using a BinaryReader to read an Excel 2007 file from an Exchange mailbox using a OWA, the file is then written to disk using a BinaryWriter. My problem is that the two files don't match when the writer finishes. Worse still Excel 2007 won't open the writen file. Previously Excel 2003 has had no problem with the solution below. And Excel 2007 doesn't have an issue if the file is an Excel 2003 format file, only if the file format is Excel 2007 (*.xlsx). BinaryReader: using(System.IO.Stream stream = resource.GetInputStream(attachedFiles[k].Address)) { using(System.IO.BinaryReader br = new System.IO.BinaryReader(stream)) { attachment.Data = new byte[attachedFiles[k].Size]; int bufPosn=0, len=0; while ((len = br.Read( attachment.Data, bufPosn, attachment.Data.Length-bufPosn )) > 0) { bufPosn += len; } br.Close(); } } BinaryWriter: FileStream fs = new FileStream(fileName, FileMode.Create); BinaryWriter binWriter = new BinaryWriter(fs); binWriter.Write( content, 0, content.Length ); binWriter.Close(); fs.Close(); Suggestions gratfully received.

    Read the article

  • Excel Range Format: Number is automatically formatted when Range::Value2 is set

    - by A9S6
    I have an Excel addin written in C# that imports a text file into Excel worksheet. Some of the fields in the file are text and some oare numbers. Problem Steps: Change the System's Regional Settings to Dutch (Belgium) Open Excel and import the file into Excel. Records contain values such as 78,1118 which gets converted to 781.118. Note that in Dutch(Belgium), COMMA is the decimal character and DOT is the thousand character. I do not require the number to be formatted automatically but just want to display whatver I get from the file (78,1118). If I set the cell's NumberFormat to "@" i.e. Text, then it displays an error (SmartTag) saying "Number stored as Text". I know I can change the settings by going to the "Options" box but I dont want to change any user options in Excel for this. I have tried setting the cell's Value2 with an "'" (apostrophe) but the same error is displayed. If I set the cell's format to something else after the value is set then the actual value changes and I loose the decimal. Is there a way in Excel to just display the value and NOT display the "Number Stored as Text" error in cell?

    Read the article

  • Inconsistency in passing objects from VBA to .NET via COM

    - by Akash
    I have the following interface defined to expose a .NET class to COM: [InterfaceType(ComInterfaceType.InterfaceIsDual)] [Guid("6A983BCC-5C83-4b30-8400-690763939659")] [ComVisible(true)] public interface IComClass { object Value { get; set; } object GetValue(); void SetValue(object value); } The implementation of this interface is trivial: [ClassInterface(ClassInterfaceType.None)] [Guid("66D0490F-718A-4722-8425-606A6C999B82")] [ComVisible(true)] public class ComClass : IComClass { private object _value = 123.456; public object Value { get { return this._value; } set { this._value = value; } } public object GetValue() { return this._value; } public void SetValue(object value) { this._value = value; } } I have then registered this using RegAsm, and tried to call it from Excel via the following code: Public Sub ComInterop() Dim cc As ComClass Set cc = New ComClass cc.SetValue (555.555) valueByGetter = cc.GetValue valueByProperty = cc.Value cc.Value = 555.555 End Sub When I step throught this code, valueByGetter = 555.5555 and valueByProperty = 555.555 as expected. However, I get an "Object required" runtime error on the final line. Why does setting the value via the setter method work but setting via the property fail? What do I have to change to get the property to work as expected?

    Read the article

  • Using VSTO in a standalone application to access Excel sheets

    - by chiccodoro
    Dear all, tried to research on that but sometimes I seem to lack some googling skills... I want to develop a (standalone) WinForms application which uses automation for communicating with Excel. I already know how to use the Interop, but I thought the VSTO tools would provide a more comfortable or sophisticated way to do that. My idea was: I could build a new standalone project with the excel references prepared. I could use a more sophisticated object model supplied by VSTO to communicate with Excel. However, my findings so far make me think that: VSTO can only be used to build add-ins/worksheets for Excel, not to build standalone application. There is no more sophisticated object model than the one provided by the Interop (which has such ugly things as a locale bug, a "Open(Missing, Missing, Missing...)" method and so on. I found a Worksheet and a Workbook class in the VSTO namespace, but as far as I understand it, these always refer to the CS classes for sheets and workbook which you implement when defining an Excel add-in or a workbook extension. - They cannot be used as comfortable wrappers in a standalone application. Can anybody confirm these statements or correct me where I am wrong? Further, if there should be a way to use VSTO and its "Workbook" class to load an excel workbook from a standalone application, then how do I do that? Thx, chiccodoro

    Read the article

  • Exporting dataset to Excel file with multiple sheets in ASP.NET

    - by engg
    In C# ASP.NET 3.5 web application, I need to export multiple datatables (or a dataset) to an Excel 2007 file with multiple sheets, and then provide the user with 'Open/Save' dialog box, WITHOUT saving the Excel file on the web server. I have used Excel Interop before. I have been reading that it's not efficient and is not the best approach to achieve this and there are more ways to do it, 2 of them being: 1) Converting data in datatables to an XML string that Excel understands 2) Using OPEN XML SDK 2.0. It looks like OPEN XML SDK 2.0 is better, please let me know. Are there any other ways to do it? I don't want to use any third-party tools. If I use OPEN XML SDK, it creates an excel file, right? I don't want to save it on the (Windows 2003) server hard drive (I don't want to use Server.MapPath, these Excel files are dynamically created, and they are not required on the server, once client gets them). I directly want to prompt the user to open/save it. I know how to do it when the 'XML string' approach is used. Please help. Thank you.

    Read the article

  • Excel VBA creating a new column with formula

    - by Amatya
    I have an excel file with a column which has date data. I want the user to input a date of their choosing and then I want to create a new column that lists the difference in days between the two dates. The Macro that I have is working but I have a few questions and I would like to make it better. Link to MWE small data file is here. The user input date was 9/30/2013, which I stored in H20 Macro: Sub Date_play() Dim x As Date Dim x2 As Date Dim y As Variant x = InputBox(Prompt:="Please enter the Folder Report Date. The following formats are acceptable: 4 1 2013 or April 1 2013 or 4/1/2013") x2 = Range("E2") y = DateDiff("D", x2, x) MsgBox y 'Used DateDiff above and it works but I don't know how to use it to fill a column or indeed a cell. Range("H20").FormulaR1C1 = x Range("H1").FormulaR1C1 = "Diff" Range("H2").Formula = "=DATEDIF(E2,$H$20,""D"")" Range("H2").AutoFill Destination:=Range("H2:H17") Range("H2:H17").Select End Sub Now, could I have done this without storing the user input date in a particular cell? I would've preferred to use the variable "x" in the formula but it wasn't working for me. I had to store the user input in H20 and then use $H$20. What's the difference between the function Datedif and the procedure DateDiff? I am able to use the procedure DateDiff in my macro but I don't know how to use it to fill out my column. Is one method better than the other? Is there a better way to add columns to the existing sheet, where the columns include some calculations involving existing data on the sheet and some user inputs? There are tons of more complicated calculations I want to do next. Thanks

    Read the article

  • Apply Font Formatting to PowerPoint Text Programatically

    - by OneNerd
    I am trying to use VBA to insert some text into a PowerPoint TextRange, I use something like this: ActiveWindow.Selection.SlideRange.Shapes("rec1").TextFrame.TextRange.Text = "Hi" However, I can't figure out how to apply bold, italic and underline programatically (I don't see a .RichText property or something similar). What I have is some simple HTML text with bold, italic and underlined text I would like to convert over. Does anyone know how to do this?

    Read the article

  • violation of primary key constraint .Cannot insert duplicate key in object using ADO

    - by CREFLY
    Hi All we are working on a users apllication using Access2003(VBA) as software language and SQL Server 2005 as database. We are using ADO method and we encounter a problem. when users create new record in a ADO Screen and they want to save the record after implementing it they receive this error : error -2147217873 violation of primary key constraint 'PK_ '.Cannot insert duplicate key in object 'Pk_...' Any help will be appreciated Thanks in advance

    Read the article

  • Macro for one-to-many splitting of Word documents

    - by Alex R
    I have a Word document which is several hundred pages long. I would like to use a macro to automatically create about a dozen or so sub-documents based on certain rules (mainly, occurrence of certain strings in each Section). Is this possible? What VBA functions should I read-up on? Does anybody know of any code examples which are even remotely similar and which I may be able to customize for my purposes? Thanks

    Read the article

  • Ensuring the contacts in a Distribution List are displayed with both name and email address

    - by hawbsl
    How can I ensure the contacts I add to an Outlook distribution list are displayed with both name and email address? These contacts may not exist in any other address book, just the distribution list. Currently they show up just as an email address (in both columns). Here's roughly the VBA we're using: Do Until RS.EOF //here's where we want to inject RS!FirstName, RS!Surname etc objRecipients.Add RS!Email objRecipients.Resolve RS.MoveNext Loop Set objDistList = contactsFolder.Items.Add("IPM.DistList") objDistList.DLName = "Whatever" objDistList.AddMembers objRecipients objDistList.Save etc

    Read the article

  • Call Single StrConn from Multiple Pages

    - by Daniel
    I have a ocnnection to SQL Server set up in my vba code. The format is: strConn = "ODBC;Driver=SQL;Server=SQL1;Database=DB1;Uid=1;Pwd=1" I have this in 4 sheets, but there will be times when I will want to change it to call from SQL2 or SQL3, and instead of changing the code on each sheet 4 times, I want to change it only once. Is there a way to set up that line to run by calling it from somewhere else or by passing in a string into the ""?

    Read the article

  • How do you link a time stamp to a cell using a userform button control? [migrated]

    - by Chad Cochrane
    Hello fellow VB Developers/Users/Hobbyists/What-Have-You! I have a user form that has two buttons: 1. Start 2. Stop When I press start, I would like it to record the current time with this format: (dd/mm/yy hh:nn:ss:) in a specific column. Then when I press the Stop Button I would like it to record the time again in the cell next to it. Then if I press start Again I would like it to record below the first cells current record. Basically I am building a timer to record data to see how long certain tasks take. I will post the excel file and provide more information were necessary. Thanks for any help provided. CURRENT CODE Public runTimer As Double Public startTime As Date Dim counter As Date Sub setStart() counter = 0 startTime = Now runTimer = Now + TimeSerial(0, 0, 1) Application.OnTime runTimer, "setStart", , True Set myTime = Sheet4.Range("F1") Set timeRng = Sheet4.Range("C8:C100") i = WorksheetFunction.CountA(timeRng) i = i + 1 Cells(i, "C") = myTime Sheet4.Cells(i, "C").NumberFormat = "yyyy/mm/dd HH:mm:ss" If i >= 2 Then Cells(i, "D8") = Cells(i, "C8") - Cells(i - 1, "C8") Sheet4.Cells(i, "C").NumberFormat = "yyyy/mm/dd HH:mm:ss" End If Application.EnableEvents = False End Sub Sub setStop() Application.OnTime runTimer, "setStop", , True Set myTime = Sheet4.Range("F1") Set timeRng = Sheet4.Range("D8:D100") i = WorksheetFunction.CountA(timeRng) i = i + 1 Application.EnableEvents = False Cells(i, "D") = myTime Sheet4.Cells(i, "D").NumberFormat = "yyyy/mm/dd HH:mm:ss" End Sub

    Read the article

  • New Office VBA site launch on MSDN

    MSDN now features a special site (also accessible via www.iheartmacros.com) dedicated to Microsoft Office VBA - an important part of the Office 2010 value.   The site presents a clear path for technically savvy users to begin learning how to customize the Office applications to meet their needs. This new MSDN site highlights content for: What you can do with VBA How to get started Key blogs VBA tips & tricks Access to a new interactive training tool, the Office Developer Atlas. In addition...Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • VBA WinHTTPRequest and submitting forms

    - by Hazerider
    Hi. I spent all day yesterday trying to figure out how to submit a form using WinHTTPRequest. I can do it pretty easily with an InternetExplorer object, but the problem is that I need to save a PDF file that gets returned, and I am not sure how to do this with the IE object. Here is the relevant HTML code snippet: <div class="loginHome-left"> <fieldset> <h3>Log in Using</h3> <form> <label for="standardLogin" accesskey="s"> <input name="useLogin" id="standardLogin" value="standard" type="radio" checked="true">Standard Login</label> &nbsp; <label for="rsaSecurID" accesskey="r"> <input name="useLogin" value="rsaSecur" type="radio" id="rsaSecurID" onclick="redirectLogin('ct_logon_securid');return false;">RSA SecurID</label> &nbsp; <label for="employeeNTXP" accesskey="e"> <input name="useLogin" id="employeeNTXP" value="employee" type="radio" onclick="redirectLogin('ct_logon_external_nt');return false; "> Employee Windows Login<br></label> </form> <br> <div class="error">Error: ...</div><br> <form onSubmit="if(validate(this)) {formSubmit();} return false;" name="passwdForm" method="post" action="/UAB/ct_logon"> <input value="custom" name="pageId" type="hidden"> <input value="custom" name="auth_mode" type="hidden"> <input value="/UAB/ct_logon" name="ct_orig_uri" type="hidden"> <INPUT VALUE="" NAME="orig_url" TYPE="hidden"> <input value="" name="lpSp" type="hidden"> <label for="user"> <strong>Username</strong> </label> <input autocomplete="off" name="user" type="text" value="" class="txtFld" onkeypress="return handleEnter(this, event);"> <br> <label for="EnterPassword"> <strong>Password</strong>&nbsp;&nbsp;(<a tabindex="-1" href="/UAB/BCResetWithSecrets">Forgot Your Password?</a>) </label> <input autocomplete="off" name="password" type="password" class="txtFld" onkeypress="return handleEnter(this, event);"> <INPUT id="rememberLogin" name="lpCookie" type="checkbox"> <label for="rememberLogin">Remember My Login Information</label><br> </form> <div class="right"> <br> <input type="image" src="/BC_S/images/bclogin/btn_login.gif" name="" value="Submit" onClick="if(validate(document.forms['passwdForm'])){formSubmit();}return false;"> </div> <div class="clearfix"></div> </fieldset> </div> In order to log in through InternetExplorer, I do the following: Sub TestLogin() Dim ie As InternetExplorer, doc As HTMLDocument, form As HTMLFormElement, inp As Variant Set ie = New InternetExplorer ie.Visible = True ie.navigate "https://URL of the login page" Do Until ie.readyState = READYSTATE_COMPLETE Loop Set doc = ie.document For Each form In doc.forms If InStr(form.innerText, "Password") <> 0 Then form.elements("user").Value = "my_name" form.elements("password").Value = "my_password" Exit For Else End If Next 'This is the unnamed input with an image that is used to submit the form' doc.all(78).Click ie.navigate "https://url of the PDF" Do Until ie.readyState = READYSTATE_COMPLETE Loop Dim filename As String, filenum As Integer filename = "somefile.pdf" filenum = FreeFile Open filename For Binary Access Write As #filenum Write #filenum, doc.DocumentElement.innerText Close #filenum ie.Quit Debug.Print Set ie = Nothing End Sub What I really would like to do is something along the lines of the following: Sub TestLogin3() Dim whr As New WinHttpRequest, postData As String whr.Open "POST", "https://live.barcap.com/UAB/ct_logon", False whr.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)" whr.setRequestHeader "Connection", "Keep-Alive" whr.Send whr.WaitForResponse postData = "user=paschom1&password=change01" 'Or the following?' postData = "user=paschom1&password=change01&orig_url=&pageId=custom&auth_mode=custom&ct_orig_uri=/BC/dispatcher&lpSp=&lpCookie=off" whr.Send postData whr.WaitForResponse Debug.Print whr.responseText End Sub It just refuses to work though. Not sure if I need to use more setRequestHeader with Content-Form or something similar, and if I do, not sure what exactly I am supposed to pass it. If anyone has any advice regarding this, it would be hugely appreciated. I could probably use a perl module to do it, but I would rather keep it all in VBA if possible. Thanks, Marc.

    Read the article

  • Excel 2010 Delete Rows with Locked Cells

    - by Roger
    I have a spreadsheet that has formulas that I want to lock, once the information in the row is completed, i.e. there is a discharge date, I want the end-user to be able to delete the row and insert it into another worksheet. I do not want to use VBA, I was successful in sequencing the protection steps, but now can not repeat the process. There has to be a way to use the protect sheet "delete rows" check box and locked cells together to enable this process

    Read the article

  • Excel - pivot values in one cell (as comma-separated value)

    - by Chris
    Excel - pivot values in one cell (as comma-separated value) I have two columns of data: Supplier1|Product1 Supplier1|Product2 Supplier1|Product4 Supplier1|Product7 Supplier2|Product3 Supplier2|Product5 I want to 'pivot' around Supplier, and give the list of products in one single cell, comma-separated e.g. Supplier1|Product1,Product2,Product4,Product7 Supplier2|Product3,Product5 There's about 1000 suppliers, and 0 < products <= 10. My current workaround involves using pivot tables, saving as CSV etc and is very messy. A non-VBA solution would be amazing.

    Read the article

  • Can't read excel file after creating it using File.WriteAllText() function

    - by Srikanth Mattihalli
    public void ExportDataSetToExcel(DataTable dt) { HttpResponse response = HttpContext.Current.Response; response.Clear(); response.Charset = "utf-8"; response.ContentEncoding = Encoding.GetEncoding("utf-8"); response.ContentType = "application/vnd.ms-excel"; Random Rand = new Random(); int iNum = Rand.Next(10000, 99999); string extension = ".xls"; string filenamepath = AppDomain.CurrentDomain.BaseDirectory + "graphs\\" + iNum + ".xls"; string file_path = "graphs/" + iNum + extension; response.AddHeader("Content-Disposition", "attachment;filename=\"" + iNum + "\""); string query = "insert into graphtable(graphtitle,graphpath,creategraph,year) VALUES('" + iNum.ToString() + "','" + file_path + "','" + true + "','" + DateTime.Now.Year.ToString() + "')"; try { int n = connect.UpdateDb(query); if (n > 0) { resultLabel.Text = "Merge Successfull"; } else { resultLabel.Text = " Merge Failed"; } resultLabel.Visible = true; } catch { } using (StringWriter sw = new StringWriter()) { using (HtmlTextWriter htw = new HtmlTextWriter(sw)) { // instantiate a datagrid DataGrid dg = new DataGrid(); dg.DataSource = dt; //ds.Tables[0]; dg.DataBind(); dg.RenderControl(htw); File.WriteAllText(filenamepath, sw.ToString()); // File.WriteAllText(filenamepath, sw.ToString(), Encoding.UTF8); response.Write(sw.ToString()); response.End(); } } } Hi all, I have created an excel sheet from datatable using above function. I want to read the excel sheet programatically using the below connectionstring. This string works fine for all other excel sheets but not for the one i created using the above function. I guess it is because of excel version problem. OleDbConnection conn= new OleDbConnection("Data Source='" + path +"';provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;";); Can anyone suggest a way by which i can create an excel sheet such that it is readable again using above query. I cannot use Microsoft InterOp library as it is not supported by my host.

    Read the article

  • Excel 2008 Cant Parse HTML

    - by VictorV
    I need to export a gridview to excel, I put the return html code from the gridview to a HtmlTextWriter and put this into the response. The result file work fine in excel, excel can parse the html and the result is readable, work perfect on excel 2003 and 2007, but in some machines with Excel 2008 (MACOS) excel shows only the raw html code and can't process this html code. Any idea to configure excel? This is the code to convert: public static void ToExcel(GridView gridView, string fileName) { HttpResponse response = HttpContext.Current.Response; response.Clear(); response.Buffer = true; fileName = fileName.Replace(".xls", string.Empty) + ".xls"; response.AddHeader("content-disposition", "attachment;filename=" + fileName); response.Charset = ""; response.ContentEncoding = Encoding.Unicode; response.BinaryWrite(Encoding.Unicode.GetPreamble()); response.ContentType = MimeTypes.GetContentType(fileName); StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); gridView.AllowPaging = false; //gridView.DataBind(); //Change the Header Row back to white color gridView.HeaderRow.Style.Add("background-color", "#FFFFFF"); //Apply style to Individual Cells for (int i = 0; i < gridView.HeaderRow.Cells.Count; i++) { gridView.HeaderRow.Cells[i].Style.Add("background-color", "yellow"); } for (int i = 0; i < gridView.Rows.Count; i++) { GridViewRow row = gridView.Rows[i]; //Change Color back to white row.BackColor = System.Drawing.Color.White; //Apply text style to each Row row.Attributes.Add("class", "textmode"); //Apply style to Individual Cells of Alternating Row if (i % 2 != 0) { for (int j = 0; j < row.Cells.Count; j++) { row.Cells[j].Style.Add("background-color", "#C2D69B"); } } } gridView.RenderControl(hw); //style to format numbers to string string style = @"<style> .textmode { mso-number-format:\@; } </style>"; response.Write(style); response.Output.Write(sw.ToString()); response.Flush(); response.End(); }

    Read the article

  • Simple Excel Export with EPPlus

    - by Jesse Taber
    Originally posted on: http://geekswithblogs.net/GruffCode/archive/2013/10/30/simple-excel-export-with-epplus.aspxAnyone I’ve ever met who works with an application that sits in front of a lot of data loves it when they can get that data exported to an Excel file for them to mess around with offline. As both developer and end user of a little website project that I’ve been working on, I found myself wanting to be able to get a bunch of the data that the application was collecting into an Excel file. The great thing about being both an end user and a developer on a project is that you can build the features that you really want! While putting this feature together I came across the fantastic EPPlus library. This library is certainly very well known and popular, but I was so impressed with it that I thought it was worth a quick blog post. This library is extremely powerful; it lets you create and manipulate Excel 2007/2010 spreadsheets in .NET code with a high degree of flexibility. My only gripe with the project is that they are not touting how insanely easy it is to build a basic Excel workbook from a simple data source. If I were running this project the approach I’m about to demonstrate in this post would be front and center on the landing page for the project because it shows how easy it really is to get started and serves as a good way to ease yourself in to some of the more advanced features. The website in question uses RavenDB, which means that we’re dealing with POCOs to model the data throughout all layers of the application. I love working like this so when it came time to figure out how to export some of this data to an Excel spreadsheet I wanted to find a way to take an IEnumerable<T> and just have it dumped to Excel with each item in the collection being modeled as a single row in the Excel worksheet. Consider the following class: public class Employee { public int Id { get; set; } public string Name { get; set; } public decimal HourlyRate { get; set; } public DateTime HireDate { get; set; } } Now let’s say we have a collection of these represented as an IEnumerable<Employee> and we want to be able to output it to an Excel file for offline querying/manipulation. As it turns out, this is dead simple to do with EPPlus. Have a look: public void ExportToExcel(IEnumerable<Employee> employees, FileInfo targetFile) { using (var excelFile = new ExcelPackage(targetFile)) { var worksheet = excelFile.Workbook.Worksheets.Add("Sheet1"); worksheet.Cells["A1"].LoadFromCollection(Collection: employees, PrintHeaders: true); excelFile.Save(); } } That’s it. Let’s break down what’s going on here: Create a ExcelPackage to model the workbook (Excel file). Note that the ‘targetFile’ value here is a FileInfo object representing the location on disk where I want the file to be saved. Create a worksheet within the workbook. Get a reference to the top-leftmost cell (addressed as A1) and invoke the ‘LoadFromCollection’ method, passing it our collection of Employee objects. Behind the scenes this is reflecting over the properties of the type provided and pulling out any public members to become columns in the resulting Excel output. The ‘PrintHeaders’ parameter tells EPPlus to grab the name of the property and put it in the first row. Save the Excel file All of the heavy lifting here is being done by the ‘LoadFromCollection’ method, and that’s a good thing. Now, this was really easy to do, but it has some limitations. Using this approach you get a very plain, un-styled Excel worksheet. The column widths are all set to the default. The number format for all cells is ‘General’ (which proves particularly interesting if you have a DateTime property in your data source). I’m a “no frills” guy, so I wasn’t bothered at all by trading off simplicity for style and formatting. That said, EPPlus has tons of samples that you can download that illustrate how to apply styles and formatting to cells and a ton of other advanced features that are way beyond the scope of this post.

    Read the article

  • How can I create a macro that acts on a relative reference rather than an absolute reference to cell A1?

    - by Bruce
    I have a master rent statement in an Excel 2007 (macro enabled) spreadsheet that shows all tenants in rows with columns formed by the months. Each tenant then has a separate rent statement sheet like the one below that pulls the data through from the master rent statement and all I do then is to copy the last 4 columns to the right and add them to the right, just renaming the month labelled as ‘rent due’ with the current month and then hiding the previous last 4 columns to the left so that the statement always shows the previous month's activity and the amount due for the current month: I used a macro to speed up the creation of these statements, but then found that in some cases the result was wrong and needed major correction because the macro use absolute references i.e. its starting position was relative to cell A1 whereas some of my rent worksheets commence from a different column and in some cases from a different column and a different row. I have tried recording the macro with 'Use relative references' but when trying to use the macro it only gets part way through its operation before it stops and the message appears: Run time error '1004' Application defined or object defined error with the option to End or Debug or go to Help and then I'm stuck as I don't know how to debug and work in VBA or understand what has gone wrong. I want to record a single macro that always remains relative to the last 'Total Due' column heading (in the sample, it’s cell FF3 but on another worksheet could be cell GA26) and thus enables me regardless of where on the worksheet the rent statement is placed to add through my recorded macro a further four columns with updated dates and a repositioned 'Total Due' summary (in the sample in cells FE23 and FF23). The contents of cells FE23 and FE22 are always the same number of rows from the 'Sample Rent Statement, Service Charge and Sub Total' rows. I've searched on the web and in the help files of Excel 2007 but have been totally stumped by this, so currently I have to re-record a quantity of macros each month to cover all of the permutations of the worksheets in my Excel rent workbook, which is starting to become pointless in terms of saving time. Does someone know a solution to this problem please?!

    Read the article

  • Excel found unreadable content in ...

    - by Rashmi Pandit
    Hi, When I open an excel file (generated through VBA code), I get an error "Excel found unreadable content in <filename>. Do you want to recover the contents?" Upon clicking yes, I get a message 'Repairs were made to PivotTable report 'pvtName' on '[filename.xls]Tab'.' The pivot table in question is generated by the VBA code. Is there a way to figure out what repairs are being done on the pivot table, so that I can make the necessary changes in the code before the file is generated? Thanks :)

    Read the article

  • How do you place an Excel Sheet/Workbook onto a C# .NET Winform?

    - by incognick
    I am trying to create a stand alone application in Visual Studio 2008 C# .Net that will house Excel Workbooks (2007). I am using Office.Interop in order to create the Excel application and I open the workbooks via Workbooks.Open(...). The Interop does not provide any functionality to "move" the workbooks onto a form so I turned to P/Invoke Win32 library. I am able to move the entire excel application onto a WinForm with great success: // pseudo code to give you the idea excel = new Excel.ApplicationClass(); SetParent(excel.Hwnd, form.handle); This allows me to customize the form and control user input. All right click commands and formula editing work properly. Now, the issue I run into is when I want to open two workbooks in two separate forms. I do this by creating two excel application classes and placing each of those in their own form. When I try to reference one workbook to another workbook via =[Book2]Sheet1!A1, for example, it does not update. This is expected as each application is running under its own thread/process. Here are the alternatives I have tried. If you have any suggestions I would be greatly appreciative.(OLE is not an option. VSTO must be available) Create a single application class and move the workbook window into my form. Results: The window moves into my form and displays correctly, however, no right click or left click works on the form and it never gains focus. (I have tried to manually set focus and it does not work either). My guess is, by moving the window outside of the XLDESK application (viewable in Spy++ for Excel Application), the workbook application (EXCEL7) does not receive the correct window messages to gain focus and to behave properly. This leads me to: Move the XLDESK window handle into my form. Results: This allows the workbook to be click-able again but also has an undesired result of moving all child windows into the same form. Create a main excel application that creates workbooks. Create a new excel application for each new window. Move the workbook under the new excel application XLDESK window. Results: This also has the same effect of the 1st option. Unable to click in the workbook. This must mean that the thread that created the workbook is also responsible for the events. Create a windows hook that watches the WndProc procedure. Results: No events watched. The targeted thread must export the hook proc in a DLL export call. Excel does not do this and thus you cannot inject into it's DLL (unless someone can prove me wrong). I am able to watch all threads within my own process but not from an outside process. Excel is created as a separate process. Subclass NativeWindow. Results: Same as #4. After I move the window into my form, all events are captured up until the mouse is directly over the excel sheet making the sheet seem unclickable. One idea I haven't tried yet is just to continually save the excel sheet as the user edits it. This should update all references but I would feel this would cause poor system performance. There will be numerous chart references as well and I'm not sure if this solution would cause problems further down the road. I think in the end, all the workbooks need to be created by the same Excel Application and then moved to get the desired results but I can't seem to find the correct way to move the windows without disabling the user input in the process. Any suggestions?

    Read the article

< Previous Page | 37 38 39 40 41 42 43 44 45 46 47 48  | Next Page >