Why Do Some Blank Cells Return Different Values in OOXML?

Problem

Some blank cells in OOXML file formats return an empty string, while other blank cells return null.  The same file in BIFF format returns only null values.

This problem occurs because OOXML (.xlsx /.xlsm) preserves any empty strings in cells when the file is saved.  When saving a file in BIFF (.xls) any cells containing an empty string will be set to a null value.

This can be a concern for users switching to the OOXML file formats. Code that checks worksheets for null values may need to be amended to account for the change in behavior.

Example 


The following code illustrates how this discrepancy might affect users:

           ExcelApplication xlapp = new ExcelApplication();
		   Workbook wb = xlapp.Open("SampleFile.xlsx")  
		   Worksheet ws = wb[0];

		   //Trim a range of cells. 
		   //Because A1 is empty, its value will be 'empty string' after trimming.
		   for(int i = 0; i<= 20; i++)
           {
		   	  for(int j = 0; j<= 20; i++)
              {
                  string value = (string)ws.Cells[i, j].Value;
				  ws.Cells[i, j].Value = value.Trim();
              }
           }

 		   //Save and reopen the file in the OOXML format
           xlapp.Save(wb, Directory + "SampleFile.xlsx");
           wb = xlapp.Open(Directory + "SampleFile.xlsx");
           ws = wb.[0];
           if (ws.Cells[0, 0].Value == null)
            {
               // This code would be reached in .xls
			   // but not in .xlsx  
            }

Users who currently check for cells containing null values may find that their code produces unexpected results when switching to OOXML files.


Solution

In order to ensure that code will return correct results when dealing with blank cells, it is important to use logic that handles all possible values.  There are 2 ways that we suggest implementing this logic.

Solution 1 – Use IsNullOrEmpty when checking for blank cells

Use logic that checks whether a cell is either null or an empty string.

Example:

            if(string.IsNullOrEmpty((string)ws.Cells[0, 0].Value))
            {
               //With this new logic, it could be either file format
                ws.Cells[1, 1].Value = "This is a .xls or an .xlsx file";   
            }

Solution 2 – Keep empty string values from being assigned to cells

Check if a cell is null before performing any operations that would assign an empty string value to a null cell.

Example:

           //Check that the cell is not empty before trimming
           if( ws.Cells[0,0].Value != null)
           {
                  string value = (string)ws.Cells[0, 0].Value;
				  ws.Cells[0, 0].Value = value.Trim();
           }
Related Information:

If your worksheet contains formulas, best practice would be to check the cell for formulas as well. More information on how to check for empty cells can be found here.


Introduction to VSTO Document-Level Customizations

For many years, the only way to add interactivity to an Office workbook or document was to use VBA Macros. However, in more recent years, Microsoft has offered a newer .NET developer tool called Visual Studio Tools for Office (VSTO). To customize a particular document or workbook using VSTO, you can use a project type called “document-level customization.” While the end-user functionality of these solutions overlap, they have very different development processes and practical implementations. In this article, we will discuss how to use VSTO document-level customizations and how they differ from their predecessor.

VSTO in a Nutshell

VSTO offers a developer two different project types: document-level customizations and application-level add-ins. Document-level customizations are projects based around a single workbook or document. Application-level add-ins, on the other hand, are add-ins affecting the UIs of Microsoft Word, Microsoft Excel, Microsoft PowerPoint, Microsoft Outlook, or Microsoft InfoPath applications themselves. In this article, we will talk about document-level customizations.

By leveraging the .NET framework, VSTO can turn a document into a full-fledged application that must be installed onto an end user’s computer. While using .NET offers a programmer nearly limitless possibilities and integration with many other services and libraries, it also means that it requires Visual Studio and strong coding skills to develop the customizations. Updates to a customization will be issued from a  server or disk where the customization is deployed. However, the updates are not without limitations. VSTO updates the code attached to a document, but it does not update the visual formatting done to workbook via Visual Studio’s Designer or Excel. All visual formatting must be done in code to be included in automatic updates. A second limitation is that a user will not be able to have more than one version of the customization on their machine at one time.

VSTO Advantages VSTO Disadvantages
  • Offers full .NET framework integration
  •  A lot of developer and client requirements
  • More robust projects
  •  Because it requires VS Premium or Ultimate, it may be more expensive to develop
  • Offers new project type: Task Pane
  •  Cannot have multiple versions of a project installed on a client machine
  •  All distributed applications will be updated to be the most recent version of the application
  • Must have strong coding skills to use
  •  Uses Visual Studio to develop code
  •  VSTO will update the code attached  to a document, but it will not update designer or template formatting
  •  Can use VBA macros inside of documents containing VSTO document-level customizations
  •  VSTO code is not located within the document, but is installed separately

Compared with VBA

VBA has been around since 1993 and is the simplest way to add interactivity to an Office document. The basic advantages and disadvantages of using VBA are outlined below: Continue reading Introduction to VSTO Document-Level Customizations

Released in OfficeWriter 8.6.1 – IEnumerable Feature

In OfficeWriter 8.6.1, we added a new feature that may have been flying under your radar, and I wanted to let you in on the story of how it came about.

When I first arrived at SoftArtisans I went through training of our entire product line.  As I was reviewing the training material, I came across the ExcelWriter Template section. I saw how to add data markers to my spreadsheet, and it seemed intuitive, so I went ahead and tried it:

ienumerable

At that moment, I was thinking “This is pretty slick. Now, I can just pass things into the spreadsheet!”  I’m not the greatest at reading documentation; I just like to learn by doing, so I opened Visual Studio and started writing code:


class Expense

{

double Amount { get; set; }

string Description = "";

bool Approved { get { return (Amount > 1000); } }

}

&nbsp;

for (int i=0; i<1000; i++)

expenses.Add(new Expense(i));

 

Looking good so far.  What I did next, however, was my downfall:


ExcelTemplate xlt = new ExcelTemplate();

xlt.BindData(expenses);

10 Tips for Handling Inherited Code

[Kate, one of our developers at SoftArtisans, was pulled onto a project to do consulting work. Below, Kate discusses her work and how she learned to handle inherited code. Read about the lessons she’s learned after being gifted a whole new project of code.]Credit: HubSpot

Recently, I inherited the code for a pretty large project, and anyone who knew the application wasn’t around when I took it over. Learning a brand new application is a daunting task – doubled if you have to learn it without any outside resources. As I tried to familiarize myself with the application, I picked up a few tricks to handling inherited code. These are a few of the things I learned along the way that will hopefully save you hours on your next undertaking.

1. Resist temptation

It can be really hard to ignore glaring implementation flaws when you look at code for the first time. Unfortunately, there are often reasons that the junky code exists in the first place. It might not be the best solution, but if it works, just leave it. Until you fully understand what each piece of code does, you might break something unintentionally by trying to fix it. Now you’ve lost time and still don’t understand the code any better. Unless it’s necessary for your current scope of work, make a tech debt note about why it’s bad code, and back away slowly.

2. Check the docs

I learn by immediately messing around in the code and doing as much damage as possible before rolling back. This isn’t really great, but hands-on learning is so natural for most technical things that we forget about reading. You. Yes, you. You are a developer so reading seems really unnecessary. Unfortunately, we still haven’t found a way to automate it, so you’ll have to do the reading yourself. Look at any documentation that might be around. It’ll suck. It won’t make a bit of sense. Then in 6 months, you’ll look at a weird method and remember that the docs said why it was like that. And you’ll think to yourself, “Ah, well, Old Fellow, looks like that reading did more than a mite bit of good!” and you’ll laugh and light up a cigar with your adoring fans swooning and giggling. Unless, you know, you’re a normal person and not a caricature of an old famous British man. Which brings me to 3…

3. Be a caricature of an old famous British man. No. Kidding. Don’t do this. (But if you do this, let’s be friends.)

3. Check the change log

It’s useful to see what might have been done recently, what kinds of issues have been encountered, and where those fixes lie. If there’s bug tracking, change logs, general progress docs, find them all. You don’t have to memorize every issue, but go over some known problems and keep yourself from making the same mistakes.

4. Be a user

It’s a lot easier to understand the code if you take some time to use the actual application. Use it like a user would, ask users (or consult the people who already did), find out why this is the way it is. There might be a good reason that all the buttons are yellow and labeled “Do not click.” It might help the users’ workflow. Make sure you know, because ultimately if the people who need this hate what you’ve done, someone else will be inheriting this code from you.

5. Just ask

When you inherit code blind, it’s awful. I mean, of course, the last ten people to look at this have all left the company/country/planet, and you’re all alone and in the dark. However, it doesn’t hurt to ask around and find out if anyone else knows what’s up. Alternately, if you have someone who knows the code, don’t get stuck in “Am I seriously doing this wrong?” hell, and just ask the question. 9 times out of 10, the code is confusing because it’s confusing code.

6. Look before you implement

It’s great when you can finally work on the code you’ve inherited. Continue reading 10 Tips for Handling Inherited Code

Creating Holiday Cards and Other Unexpected OfficeWriter Projects

Last week, our VP of Development Sam and Senior Sales Engineer Chad were challenged to look at different ways to use OfficeWriter. The result? They put together a project designed to keep you in touch with your friends and family this holiday season. They looked at using OfficeWriter’s mail merge feature in a new way. Plus, they took that one step further, looking at how the technologies from this project can be applied to business applications within your company. Before heading home for the holidays, take a little inspiration from this behind-the-scenes video of unexpected ways to use OfficeWriter in building your reports and company documents.

Read the original post, get the code, and take a behind-the-scenes tour of the technologies it runs on.

Embedly Powered

via Vimeo

Want to get straight to the point? Skip to the end of the video to discover how this project could be applied to your business.

How I Learned to Love My Data: Gobbles and Gobbles of Data

Love your dataLet me preface this by saying I am a communications major, a lover of language and all things related to the humanities, following the auspices of the left brain. Science, statistics, numbers, data – that was for my logically-minded friends. Attending a research university, I was constantly surrounded by studies, which as you guessed it, are based off of piles and piles of data. It’s not that I didn’t understand the importance of data, it’s that I just never loved it. As a communications major I tended to shy away from numbers. (Okay, more like run flailing in the opposite direction as though my life depended on it.) Turns out numbers are a very real part of marketing, if not the crux of every marketing campaign. It allows you to measure what is working for your goals and what needs adjustment.

Generally speaking, I love the insights it gives, the conclusions it reaches. I just don’t enjoy the process of data collection in order to reach those conclusions. But who does? With data tied to many different sources, and housed in varying formats, it’s not easy to make it come together in one simple report. I’d like my data handed to me, preferably on a silver platter. Yes, well, that’s not how it works. And that’s not how it should work. In order to really understand the insights and not be misled by false assumptions, you should be able to understand where this data is coming from, how things are being measured, and what the goals are behind it.

Working at a software company, whose product deals with a ton of data and is designed for companies processing it to perform their reporting, I’ve had to become more comfortable with it. In any job this is a valuable skill to possess. Being able to deliver reports and present your work and results to the company/client/manager is a very necessary part of any business, and one that CEOs and execs place a lot of stake in. Not only that, it puts a tangible number to your work you can point to, to assess improvements and successes.

While there is this necessary business side to data collection, that doesn’t have quite the same motivation to learning to fully appreciate it. As I dove deeper into the weeds – spreadsheets, SSRS, Big Data, dark data, and servers – I discovered the ways in which people were using these numbers, the artful approach to using and displaying the information that is being collected. My coworkers showed me spreadsheets can be the springboard for masterpieces (see: Baking Cookies in Excel and Making Art with Excel). Speaker and data visualization blogger, Cole Nausbaumer, showed me you can infuse creativity into numbers. In her Storytelling with Data blog, she shows the meshing of the creativity behind presenting your data in a way people can relate to and process it: the age old art of storytelling. Now that is something to which I can relate. (If you haven’t yet, you should read her blog, and pick up tricks on data visualization.)

Along the same lines of displaying your data, Continue reading How I Learned to Love My Data: Gobbles and Gobbles of Data

How to Use Worksheet Protection Properties In ExcelWriter

How to Use Worksheet Protection Properties In ExcelWriter

In ExcelWriter 8.6.1, the ability to set specific worksheet protection properties was added with the new Sheet Protection Object. Worksheet Protection Properties allow the user to add permissions to do certain actions on protected worksheets.

The Excel Protection Properties

Excel Worksheet Protection Property ExcelWriter SheetProtection Object Property
Select Locked cells SheetProtection.AllowSelectLockedCells
Select Unlocked Cells SheetProtection.AllowSelectUnlockedCells
Format Cells SheetProtection.AllowFormatCells
Format columns SheetProtection.AllowFormatColumns
Format Rows SheetProtection.AllowFormatRows
Insert Columns SheetProtection.AllowInsertColumns
Insert Rows SheetProtection.AllowInsertRows
Insert Hyperlinks SheetProtection.AllowInsertHyperlinks
Delete Columns SheetProtection.AllowDeleteColumns
Delete Rows SheetProtection.AllowDeleteRows
Sort SheetProtection.AllowSort
Use Autofilter SheetProtection.AllowUseAutoFilter
Use PivotTable reports SheetProtection.AllowUsePivotTableReports
Edit Objects Not Supported by ExcelWriter
Edit Scenarios Not Supported by ExcelWriter

Protection Properties Limitations

Microsoft Excel has a limitation on four of the protection properties: AllowSort, AllowDeleteColumns, AllowDeleteRows, and AllowInsertHyperlinks. These properties require that affected cells be editable when the worksheet is locked. This is because these properties entirely remove cells or alter the content of cells that are protected. Therefore, in order to use the properties you must unlock cells, put cells in an editable range, or use a macro.

Using the Protection Properties in Excel Writer

Steps to Use Protection Properties in ExcelWriter: 

  1. Create a new sheet protection object
  2. Set the worksheet protection properties as desired. By default, Select Locked cells and Select Unlocked Cells are set to true
  3. Call Protect() on the worksheet Continue reading How to Use Worksheet Protection Properties In ExcelWriter

Troubleshooting Tools to Give Thanks to this Thanksgiving

thanskgiving

[Once a week I snoop around the office, bothering my coworkers with questions on what they’re reading, listening to, consuming, or any other random inquiries I’d like to subject them to. Sometimes they even respond.]

Debug, de-stress. This week we’re giving thanks to these troubleshooting tools that keep us sane. We chose troubleshooting tools not for the alliteration value (though, that was a happy coincidence), but to find time-saving ways you can stay on top of your coding projects this holiday season. See below as we show our appreciation for developer tools we can’t live without. What other tools do you use to debug and de-stress? Tell us about them in the comments section below.

Chad, Sr. Sales Engineer

Fiddler2 helps make debugging web service calls easy.

Paula, Director of HR

Don’t even need to think about that one – System Restore Manager!

Ozgur, Development

I’d definitely list Fiddler and WireShark as some of the top troubleshooting tools that I am thankful for.

Aviva, VP of Technical Services

I mostly use the debugger in Visual Studio or custom code I write myself. Although it’s not a development tool, Procmon can be helpful, for monitoring activities on the filesystem and registry.

Stephanie, Technical Services

Total Commander is great. The program does a ton of stuff, but I really like its Continue reading Troubleshooting Tools to Give Thanks to this Thanksgiving

Create your Holiday Cards with OfficeWriter, The Sequel

seasonsgreetingsThe holiday season is back! Stores are stocking their shelves with the season’s must-haves and calendars are quickly filling up with travel and office parties. With all the hustle, bustle and festivities, occasionally remember to send out those holiday cards and thank-you notes gets lost in the tinsel and taffeta. Well, you’re in luck, because this year we’ve put together a project for you to easily send out holiday thank-you notes and cards the nostalgic, old-fashioned way.

Last year, Sam showed us how to Automate Your Holiday Cards with OfficeWriter, and this year we’ve added thank-you notes to the mix. So you can spend less time on holiday prep and more time on the things that matter most – friends and family.

Using a few built-in tools with the .NET Framework, OfficeWriter, and templates, you can personalize every card for each one of your friends and family. See the example below. Then make your own by following these steps:

STEP 1 – DOWNLOAD OFFICEWRITER:

To get started, you will need to have OfficeWriter installed in order to be able to use the sample code below. In my solution, I used OfficeWriter and its built-in WordTemplate functionality to do a server-side mail merge. If you do not have OfficeWriter, you can download a free evaluation here.

STEP 2 – DOWNLOAD SAMPLE CODE:

Next, you will need the sample code. Download the sample solution here. This solution comes bundled with:

  • Sample code
  • Easily modifiable templates for holiday cards, mailing labels, and thank-you letters.
  • Dummy data from a Gmail Contact Export

Open the solution, run the generator, and you can see the three items:

SAMPLE OUTPUT:

SAMPLE CODE:

OfficeWriter makes it easy to generate the finished holiday cards, labels, and thank-you cards. With about 5 lines of OfficeWriter code for each template, within minutes you can go from nothing to a finished, picture-perfect file. The sample code below is a simple way to parameterize the code to handle all of our template files. Continue reading Create your Holiday Cards with OfficeWriter, The Sequel

RetroTech Vol 1: Yuri Broze, Datasciencehead at Nomi

[Welcome to RetroTech, a joint blog series with Skimbox, where we journey back in time to an era of floppy disks, the Atari 800, and that unmistakable clicking sound of dial-up. We’re digging up the good ol’ days with interviews from tech’s most staunch patrons and giving you a glimpse of their technological firsts.]

Interviews with TechFrom Proust and his madeleines to Buzzfeed and early Britney, if there’s one thing that unites us, it’s our shared affection for nostalgia. And tech nostalgia is, at least in our opinion, a particularly rich strain, because it combines memories with cluck-tongued humor. So we decided to mine it with RetroTech, an interview series about personal technological firsts.

To kick of the series, we turned to Yuri Broze. Yuri is a number of things, including: maestro of the right and left brains, unicyclist, pianist, and world-class whistler. He may not be the only data scientist with a PhD in Music Psychology, but he is the only one we know.

First screen name: dkcrulz. Short for “Donkey Kong Country Rules.” Yuri picked it up at age 11, in 1994, right after Donkey Kong Country came out.

First email address: dkcrulz@aol.com.

First computer: An IBM Compatible running MS DOS. “I would write poetry on it and have every other line come back ‘bad command or file name.’”

First video/computer game: Lemonade Stand for Apple 2. (Ed — this looks like the least fun computer game ever, and I say that as a person who wrote an execrable version of Pong.) Continue reading RetroTech Vol 1: Yuri Broze, Datasciencehead at Nomi

Blogged