This command requires at least two rows of source data - c#

I am getting this error:
This command requires at least two rows of source data. You cannot use the command on a selection in only one row. Try the following:
- If you're using an advanced filter, select a range of cells that contains at least two rows of data. Then click the Advanced Filter command again.
- I you're creating a PivotTable, type a cell reference or select a range that includes at least two rows of data
intermittently on this line of code:
xlWorkBook.RefreshAll();
There are two worksheets. One has a pivot table and one has raw data. Sometimes there is only one row of data. For multiple rows of data the line of code above always works; however, for only 1 row of data, the code above sometimes works, and sometimes I get the error message above.
In addition to this, the worksheet containing the pivot table is not refreshed; however, if I re-open the file, it also does not refresh, unless I explicitly refresh it manually.
What is going on here? Why am I getting this error only sometimes?
Thank you so much for your guidance.
if at all helpful, i am including the entire method:
private void SortandCreateFile(string column, string email, string emailStartPos) {
string replacetext = "";
try {
var valueRange = xlWorkSheet.get_Range(column + emailStartPos, column + range.Rows.Count.ToString());
var deleteRange = valueRange;
xlApp.Visible = false;
int startpos = 0;
int endPos=0;
bool foundStart = false;
Excel.Range rng = xlWorkSheet.get_Range(column + "1", column + range.Rows.Count.ToString());
string tempstring = "d";
int INTemailStartPos = Convert.ToInt16(emailStartPos);
for (int rCnt = INTemailStartPos; rCnt <= rng.Count; rCnt++) {
Excel.Range cell = (Excel.Range)rng[rCnt, 1];
try {
if (cell.Value2 != null)
tempstring = cell.Value2.ToString();
else {
startpos = rCnt;
releaseObject(cell); /////////
break;
}
}
catch (Exception ee)
{
MessageBox.Show(ee.ToString());
}
//grab the text from column link texdtbox
Excel.Range rngLinkColumn;
Excel.Range replacetextcell=null;
if (FormControls.ColumnLink.Length > 0) {
rngLinkColumn = xlWorkSheet.get_Range(FormControls.ColumnLink + "1", FormControls.ColumnLink + range.Rows.Count.ToString());
replacetextcell = (Excel.Range)rngLinkColumn[rCnt, 1];
}
//locate email
if (cell.Value2.ToString() == email ) {
//we found the starting position of the email we want!
//this will tell us which row of data to start from
startpos = rCnt;
if (FormControls.ColumnLink.Length > 0)
replacetext = replacetextcell.Value2.ToString();
releaseObject(cell); /////////
break;
}
releaseObject(cell);
}
int foundstartminusONE = startpos - 1;
int rngcount = rng.Count + INTemailStartPos;
//delete everything from the top UNTIL the row of the email address that we need
if (startpos != INTemailStartPos) {
deleteRange = xlWorkSheet.get_Range(column + INTemailStartPos.ToString() + ":" + "CF" + foundstartminusONE.ToString(), Type.Missing);
deleteRange = deleteRange.EntireRow;
deleteRange.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);
}
for (int rCnt = INTemailStartPos; rCnt <= rng.Count; rCnt++) {
Excel.Range cell = (Excel.Range)rng[rCnt, 1];
try {
if (cell.Value2 != null )
tempstring = cell.Value2.ToString();
else {
endPos = rCnt - 1;
releaseObject(cell);////////
break;
}
}
catch (Exception ee) {
//MessageBox.Show(ee.ToString());
}
//locate email
if (cell.Value2.ToString() != email ) {
//we found where the last email address is that we need
//this is where the issue is occurring i think with the deleting the last row
endPos = rCnt;
releaseObject(cell);////////
break;
}
releaseObject(cell);
}
//delete all the stuff AFTER the email address that we need
if (endPos != 0) {
deleteRange = xlWorkSheet.get_Range(column + endPos + ":" + "CF" + rngcount.ToString(), Type.Missing);
deleteRange = deleteRange.EntireRow;
deleteRange.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);
}
//when the user opens the excel file, we want the focus to be here
var rangehome = xlWorkSheet.get_Range(FormControls.FocusOn, FormControls.FocusOn);
xlWorkSheet.Activate();
rangehome.Select();
string filename = xlWorkBook.Path + #"\" + email + ".xlsx";
string fileSubstring = filename.Substring(0, filename.IndexOf(".xlsx"));
string randomfileString = Guid.NewGuid().ToString("N").Substring(0, 10) + ".xlsx";
string targetfilenameRename = fileSubstring + randomfileString;
//((Excel.Worksheet)this.Application.ActiveWorkbook.Sheets[FormControls.WorksheetFocus]).Activate();
//((Excel.Worksheet)Excel.Application.ActiveWorkbook.Sheets[1]).Activate();
Excel.Worksheet xlWorkSheetFocus = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(FormControls.WorksheetFocus);
xlWorkSheetFocus.Activate();
xlWorkBook.SaveAs(targetfilenameRename, Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
false, false, Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Excel.XlSaveConflictResolution.xlLocalSessionChanges, Type.Missing, Type.Missing);
try {
xlWorkBook.RefreshAll();
}
catch { }
xlWorkBook.Save();
string targetfile = xlWorkBook.Path + #"\" + FormControls.FileName + " - "
+ email.Substring(0, email.IndexOf("#")) + ".xlsx";
System.IO.File.Copy(targetfilenameRename, targetfile, true);
string body = FormControls.eMailBody;
body = body.Replace("%replacetext%", replacetext);
//replace %replacetext% in body
string targetfileSubstring = targetfile.Substring(0, targetfile.IndexOf(".xlsx"));
string randomString = Guid.NewGuid().ToString("N").Substring(0, 10)+".xlsx";
string targetfileRename = targetfileSubstring+randomString;
while (true) {
try {
SendEmail(targetfile, email, FormControls.eMailSubject, body,FormControls.eMailFrom);
}
catch (Exception ee) {
MessageBox.Show(ee.ToString());
continue;
}
// all is good
break;
}
releaseObject(valueRange);
releaseObject(deleteRange);
File.Copy(targetfile, targetfileRename, true);
}
catch (Exception e) {
MessageBox.Show(e.ToString());
}
finally {
//DisposeMe();
// Release all COM RCWs.
// The "releaseObject" will just "do nothing" if null is passed,
// so no need to check to find out which need to be released.
// The "finally" is run in all cases, even if there was an exception
// in the "try".
// Note: passing "by ref" so afterwords "xlWorkSheet" will
// evaluate to null. See "releaseObject".
releaseObject(range);
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
// The Quit is done in the finally because we always
// want to quit. It is no different than releasing RCWs.
if (xlApp != null) {
xlApp.Quit();
}
releaseObject(xlApp);
}
}

The only way I could replicate this error with a pivot table was by attempting to create one off a range that didn't have column headers, just like on the screenshot from Stephan1010's answer.
In the GetPivotData Excel function, pivot fields are referred to by their names (=GETPIVOTDATA("EmailAddress",$A$3)); thus, it makes sense to disallow a data source that wouldn't have them.
The solution would be to pivot over a ListObject instead of a Range - in Excel when you select, say, range $A$1:$C$1 and format as table (from the Ribbon), the table that results will span $A$1:$C$2; the contents of the first row becomes the column headers and the second row is a valid, empty record. Interesting to note that this happens (the 2-row span) regardless of whether or not you check the "My table has headers" checkbox (the data will be moved to the first row and the table will contain default "Column1"-"Column2"-"Column3" headers if the checkbox is cleared).
In other words, a ListObject is always a valid data source for a pivot table, while a Range may not contain enough rows. Also if you don't have column headers and you create a pivot table with range $A$1:$C$2, the record at $A$1:$C$1 will be used as column headers, which means that first record is lost.
From the code you have supplied I would presume the pivot table is already present and connected to some [named?] range in a template workbook that contains the macro. Turning your range into a table might be as trivial as selecting format as table from the Ribbon. And then you could have code like this to remove all unnecessary rows while still keeping a valid data source for the pivot table:
public void DeleteExtraTableRows(string emailAddress, Excel.ListObject table)
{
try
{
var rowIndex = 0;
var wasDeleted = false;
while (rowIndex <= table.ListRows.Count)
{
if (!wasDeleted) rowIndex++;
var row = table.ListRows[rowIndex];
var range = (Excel.Range)row.Range.Cells[1, 1];
var value = range.Value2;
if (value != null && !string.Equals(emailAddress, value.ToString()))
{
row.Delete();
wasDeleted = true;
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message + "\n\n" + e.StackTrace);
}
}
There is also a possibility that the email is never found in the loop's if (cell.Value2.ToString() == email ) condition, which would end up deleting all rows from your range - even if the only difference is an extra space at the end of the in-cell value. With the above code, even if all email addresses get deleted the data source remains a valid one for a pivot table that would be connected to it.
EDIT:
In Excel you turn a Range into a ListObject by selecting the range in question and clicking the Format as table Ribbon button, from the Home tab. Alternatively you can create one like this:
var range = ((Excel.Range)(worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[3, 1]]));
var table = worksheet.ListObjects.Add(SourceType: Excel.XlListObjectSourceType.xlSrcRange, Source: range,
XlListObjectHasHeaders: Excel.XlYesNoGuess.xlYes);
table.TableStyle = "TableStyleMedium3";
In code, you can access all ListObjects on a worksheet using the ListObjects property:
var worksheet = (Excel.Worksheet) Globals.ThisAddIn.Application.ActiveSheet;
var tables = worksheet.ListObjects;
Then, you can access a specific ListObject /table with several different ways:
var myTable = tables[1];
var myTable = tables.Item["Table1"];
var myTable = tables.OfType<Excel.ListObject>().FirstOrDefault(t => t.Name == "Table1");
As rows are added from the table, the actual range it refers to will be expanded accordingly; use myTable.Range to access the range in question.

i suppose this situation occurs because of the pivot tables you got.
cause refresh all will trigger pivot table's refresh command too.
look at the code below. It may give you an idea about it. Its not about 1 row im sure. i checked it everthing works just fine its most posibly caused by pivot tables.
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook xlWorkbook = xlApp.Workbooks.Open("some.xlsx");
// For each worksheet we got
foreach (Microsoft.Office.Interop.Excel.Worksheet worksheet in xlWorkbook.Sheets)
{ // and each pivot table in each worksheet
foreach (Microsoft.Office.Interop.Excel.PivotTable pivot in worksheet.PivotTables())
{ // disable BackgroundQuery
pivot.PivotTableWizard(BackgroundQuery: false);
}
}
// try to refresh all sheet
try { xlWorkbook.RefreshAll(); } catch { }
// then save
xlWorkbook.Save();

The obvious answer seems to be that sometimes you have one row of data as the source for your pivot table and sometimes you don't - even when you think you still do. I have not been able to create a pivot table(or change the source of a pivot table) to one row of data:
but if you are able to somehow figure out a way to do this then you have found your answer. There is no reason you can't have one row of data as your source just from a practical/theoretical perspective, but it looks like excel tries to prevent that from happening(maybe because the code assumes two rows). So if you do find a way, then it is probably a bug. Good Luck.

Related

Outlook new email to Excel row

I want to create a C# Console app (or a service - not sure how to develop a service yet) that:
1) Knows when a new email is received in Inbox>LOTALogs folder. This email is sent by a mobile application and includes an attachment and some issues that the customer experienced.
2) Takes the new email content, which is comma-separated, parses and appends the content into an Excel worksheet that already has the columns set up.
I managed to create:
1) The parser:
public static string[] emailContentsArray()
{
string content = "Username = Customer1,User ID = 362592,Unit ID = 805618,Date = Mar 12, 2017,Device = Android LGE LG-H990,OS version = 7.0 (API 24),App version = 1.0.0.56,Description = some description,Message = some message";
string[] contentArray = content.Split(',');
// Case where date format includes another comma
if (contentArray.Length > 10)
{
// Parsing headers
contentArray[0] = contentArray[0].Substring(11);
contentArray[1] = contentArray[1].Substring(10);
contentArray[2] = contentArray[2].Substring(10);
contentArray[3] = contentArray[3].Substring(7) + ", " + contentArray[4].Substring(1);
contentArray[4] = contentArray[5].Substring(9);
contentArray[5] = contentArray[6].Substring(13);
contentArray[6] = contentArray[7].Substring(14);
contentArray[7] = contentArray[8].Substring(14);
contentArray[8] = contentArray[9].Substring(10);
contentArray[9] = null;
for (int i = 0; i < contentArray.Length; i++)
{
Console.Write(contentArray[i] + ",");
}
}
//else
//{
//}
return contentArray;
}
2) Accessed the folder and counted the number of items:
public static string[] emailContent()
{
string[] content = null;
Microsoft.Office.Interop.Outlook.Application app = null;
Microsoft.Office.Interop.Outlook.NameSpace ns = null;
Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = null;
Microsoft.Office.Interop.Outlook.MAPIFolder logFolder = null;
app = new Microsoft.Office.Interop.Outlook.Application();
ns = app.GetNamespace("MAPI");
inboxFolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
logFolder = app.ActiveExplorer().CurrentFolder = inboxFolder.Folders["LOTALogs"];
int itemCount = logFolder.Items.Count;
Console.WriteLine("\n\nFolder Name: {0}, Num Items: {1}\n", logFolder.Name, itemCount);
return content;
}
3) Opened and printed the contents of the spreadsheet:
Excel.Application xlApp = new Excel.Application();
string path = "C:\\SomeUser\\BugReports";
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(#path);
Excel.Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
for (int i = 1; i <= xlRange.Row + xlRange.Rows.Count - 1; i++)
{
for (int j = 1; j <= xlRange.Column + xlRange.Columns.Count - 1; j++)
{
if (j == 1)
Console.Write("\r\n");
if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null)
Console.Write(xlRange.Cells[i, j].Value2.ToString() + "\t");
}
}
xlWorkbook.Save();
xlWorkbook.Close();
xlApp.Quit();
Console.ReadLine();
I am a little lost now :)
I still need to:
1) Create an event listener (I think that's what it's called) so I can tell the email body parser to go fetch the email contents.
2) Extract the email body from the email.
Got this using
Console.WriteLine(logFolder.Items[1].Body);
3) Take the email content and append it to the spreadsheet.
4) Should I create this as a Windows Service?
PS - I am not a developer, just fiddling around with code and trying to be as efficient as possible. I don't want to fill this spreadsheet out manually when there's a technological solution in sight. Please comment if you have any suggestions on being more efficient with the code and model it differently.
Looks solid to me. I'd refrain from the service, but it greatly depends on your users. Unless your customer really wants to be "blind" from the whole process, it adds a lot of unwarranted complications.
As for appending to the spreadsheet...
int lastRow = xlWorksheet.UsedRange.Rows;
Excel.Range xlRange = xlWorksheet.Cells[lastRow + 1, 1];
xlRange.Value = stuffFromInbox;
If you're only adding the one item to the spreadsheet, this will work fine. For mass read/write operations with the spreadsheet (like your "Opened and printed the contents of the spreadsheet"), it would be much more efficient to read the Value or Value2 of the entire Range into a object[,]. Then iterate through the local array.

User input to change column header text in DataGrid

I am creating a DataGrid by importing an excel file. I want users manually to be able to change column names from the application.
Edit: Workaround at the bottom
My desktop app will have below logic:
Load excel file and display table in DataGrid
Manually change Column names to match fixed text. (e.x. Column "PricesZZZ" renamed to "Prices", "LeadTimeXXX to "LeadTime")
Export DataGrid to new excel template with only relevant columns that are matched by fixed text (thus the need to have correct
names).
Excel file can have multiple columns and only several of those columns have relevant information and the only way to identify them is to match header name or some other way have user "tell" program which column holds which information.
I need to find a way to change Column name based on user input as I think it's most straightforward. I'm new to c# so sorry if my thinking is a little backwards.
Below is the code snippet I have so far. Might not be relevant for this specific problem, but may help visualize. I use EPPlus library
Import excel
private void btnOpenXL_Click(object sender, RoutedEventArgs e)
{
// Create OpenFileDialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
// Set filter for file extension and default file extension
dlg.DefaultExt = ".xls";
dlg.Filter = "Excel Files|*.xlsx;*.xls;*.xlsm;*.csv";
// Display OpenFileDialog by calling ShowDialog method
Nullable<bool> result = dlg.ShowDialog();
// Get the selected file name
if (result == true)
{
// Open document
string filename = dlg.FileName;
//call another class to draw the table
dataGrid.ItemsSource = GetDataTableFromExcel(filename).DefaultView;
MessageBox.Show("import done");
}
}
public static DataTable GetDataTableFromExcel(string path, bool hasHeader = true)
{
using (var pck = new OfficeOpenXml.ExcelPackage())
{
using (var stream = File.OpenRead(path))
{
pck.Load(stream);
}
var ws = pck.Workbook.Worksheets.First();
DataTable tbl = new DataTable();
foreach (var firstRowCell in ws.Cells[1, 1, 1, ws.Dimension.End.Column])
{
tbl.Columns.Add(hasHeader ? firstRowCell.Text : string.Format("Column {0}", firstRowCell.Start.Column));
}
var startRow = hasHeader ? 2 : 1;
for (int rowNum = startRow; rowNum <= ws.Dimension.End.Row; rowNum++)
{
var wsRow = ws.Cells[rowNum, 1, rowNum, ws.Dimension.End.Column];
DataRow row = tbl.Rows.Add();
foreach (var cell in wsRow)
{
row[cell.Start.Column - 1] = cell.Text;
}
}
return tbl;
}
}
Export excel
private void btnExportToXL_Click(object sender, RoutedEventArgs e)
{
DataTable dataTable = new DataTable();
dataTable = ((DataView)dataGrid.ItemsSource).ToTable();
ExportDataTableToExcel(dataTable);
MessageBox.Show("export done");
}
public void ExportDataTableToExcel(DataTable dataTable)
{
string path = "C:\\test";
var newFile = new FileInfo(path + "\\" +
DateTime.Now.Ticks + ".xlsx");
using (ExcelPackage pck = new ExcelPackage(newFile))
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Sheet1");
ws.Cells["A1"].LoadFromDataTable(dataTable, true);
pck.Save();
System.Diagnostics.Process.Start(newFile.ToString());
}
}
EDIT:
Workaround by double clicking on any cell in datagrid:
private void dataGrid_MouseDoubleClick(object sender, RoutedEventArgs e)
{
if (dataGrid.SelectedIndex == -1) //if column selected, cant use .CurrentColumn property
{
MessageBox.Show("Please double click on a row");
}
else
{
DataGridColumn columnHeader = dataGrid.CurrentColumn;
if (columnHeader != null)
{
string input = Interaction.InputBox("Title", "Prompt", "Default", 0, 0);
columnHeader.Header = input;
}
}
}
You can change the column names of the datagridview. But note, that this change is limited only to the grid and not it's data source. So in a nutshell, for simple representational purposes, you can use the following code:
dataGrid.Columns[i].HeaderText = "New Column Name"; //i is the index of the column
You can call this code form a Button click event of a Text change event of the input where the user provides the header name. Additionally, if you have the column names beforehand, you can replace then column headers with new values right after the data source has been bound to the grid. Change the headers after this line:
dataGrid.ItemsSource = GetDataTableFromExcel(filename).DefaultView;
//Set new column names here

How to read excel file in asp.net

I am using Epplus library in order to upload data from excel file.The code i am using is perfectly works for excel file which has standard form.ie if first row is column and rest all data corresponds to column.But now a days i am getting regularly , excel files which has different structure and i am not able to read
excel file like as shown below
what i want is on third row i wan only Region and Location Id and its values.Then 7th row is columns and 8th to 15 are its values.Finally 17th row is columns for 18th to 20th .How to load all these datas to seperate datatables
code i used is as shown below
I created an extension method
public static DataSet Exceltotable(this string path)
{
DataSet ds = null;
using (var pck = new OfficeOpenXml.ExcelPackage())
{
try
{
using (var stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
pck.Load(stream);
}
ds = new DataSet();
var wss = pck.Workbook.Worksheets;
////////////////////////////////////
//Application app = new Application();
//app.Visible = true;
//app.Workbooks.Add("");
//app.Workbooks.Add(#"c:\MyWork\WorkBook1.xls");
//app.Workbooks.Add(#"c:\MyWork\WorkBook2.xls");
//for (int i = 2; i <= app.Workbooks.Count; i++)
//{
// for (int j = 1; j <= app.Workbooks[i].Worksheets.Count; j++)
// {
// Worksheet ws = app.Workbooks[i].Worksheets[j];
// ws.Copy(app.Workbooks[1].Worksheets[1]);
// }
//}
///////////////////////////////////////////////////
//for(int s=0;s<5;s++)
//{
foreach (var ws in wss)
{
System.Data.DataTable tbl = new System.Data.DataTable();
bool hasHeader = true; // adjust it accordingly( i've mentioned that this is a simple approach)
string ErrorMessage = string.Empty;
foreach (var firstRowCell in ws.Cells[1, 1, 1, ws.Dimension.End.Column])
{
tbl.Columns.Add(hasHeader ? firstRowCell.Text : string.Format("Column {0}", firstRowCell.Start.Column));
}
var startRow = hasHeader ? 2 : 1;
for (var rowNum = startRow; rowNum <= ws.Dimension.End.Row; rowNum++)
{
var wsRow = ws.Cells[rowNum, 1, rowNum, ws.Dimension.End.Column];
var row = tbl.NewRow();
foreach (var cell in wsRow)
{
//modifed by faras
if (cell.Text != null)
{
row[cell.Start.Column - 1] = cell.Text;
}
}
tbl.Rows.Add(row);
tbl.TableName = ws.Name;
}
DataTable dt = RemoveEmptyRows(tbl);
ds.Tables.Add(dt);
}
}
catch (Exception exp)
{
}
return ds;
}
}
If you're providing the template for users to upload, you can mitigate this some by using named ranges in your spreadsheet. That's a good idea anyway when programmatically working with Excel because it helps when you modify your own spreadsheet, not just when the user does.
You probably know how to name a range, but for the sake of completeness, here's how to name a range.
When you're working with the spreadsheet in code you can get a reference to the range using [yourworkbook].Names["yourNamedRange"]. If it's just a single cell and you need to reference the row or column index you can use .Start.Row or .Start.Column.
I add named ranges for anything - cells containing particular values, columns, header rows, rows where sets of data begin. If I need row or column indexes I assign useful variable names. That protects you from having all sorts of "magic numbers" in your spreadsheet. You (or your users) can move quite a bit around without breaking anything.
If they modify the structure too much then it won't work. You can also use protection on the workbook and worksheet to ensure that they can't accidentally modify the structure - tabs, rows, columns.
This is loosely taken from a test I was working with last weekend when I was learning this. It was just a "hello world" so I wasn't trying to make it all streamlined and perfect. (I was working on populating a spreadsheet, not reading one, so I'm just learning the properties as I go.)
// Open the workbook
using (var package = new ExcelPackage(new FileInfo("PriceQuoteTemplate.xlsx")))
{
// Get the worksheet I'm looking for
var quoteSheet = package.Workbook.Worksheets["Quote"];
//If I wanted to get the text from one named range
var cellText = quoteSheet.Workbook.Names["myNamedRange"].Text
//If I wanted to get the cell's value as some other type
var cellValue = quoteSheet.Workbook.Names["myNamedRange"].GetValue<int>();
//If I had a named range and I wanted to loop through the rows and get
//values from certain columns
var myRange = quoteSheet.Workbook.Names["rangeContainingRows"];
//This is a named range used to mark a column. So instead of using a
//magic number, I'll read from whatever column has this named range.
var someColumn = quoteSheet.Workbook.Names["columnLabel"].Start.Column;
for(var rowNumber = myRange.Start.Row; rowNumber < myRange.Start.Row + myRange.Rows; rowNumber++)
{
var getTheTextForTheRowAndColumn = quoteSheet.Cells(rowNumber, someColumn).Text
}
There might be a more elegant way to go about it. I just started using this myself. But the idea is you tell it to find a certain named range on the spreadsheet, and then you use the row or column number of that range instead of a magic row or column number.
Even though a range might be one cell, one row, or one column, it can potentially be a larger area. That's why I use .Start.Row. In other words, give me the row for the first cell in the range. If a range has more than one row, the .Rows property indicates the number of rows so I know how many there are. That means someone could even insert rows without breaking the code.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
namespace ReadData
{
public partial class ImportExelDataInGridView : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnUpload_Click(object sender, EventArgs e)
{
//Coneection String by default empty
string ConStr = "";
//Extantion of the file upload control saving into ext because
//there are two types of extation .xls and .xlsx of excel
string ext = Path.GetExtension(FileUpload1.FileName).ToLower();
//getting the path of the file
string path = Server.MapPath("~/MyFolder/"+FileUpload1.FileName);
//saving the file inside the MyFolder of the server
FileUpload1.SaveAs(path);
Label1.Text = FileUpload1.FileName + "\'s Data showing into the GridView";
//checking that extantion is .xls or .xlsx
if (ext.Trim() == ".xls")
{
//connection string for that file which extantion is .xls
ConStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (ext.Trim() == ".xlsx")
{
//connection string for that file which extantion is .xlsx
ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
//making query
string query = "SELECT * FROM [Sheet1$]";
//Providing connection
OleDbConnection conn = new OleDbConnection(ConStr);
//checking that connection state is closed or not if closed the
//open the connection
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
//create command object
OleDbCommand cmd = new OleDbCommand(query, conn);
// create a data adapter and get the data into dataadapter
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
//fill the excel data to data set
da.Fill(ds);
if (ds.Tables != null && ds.Tables.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
{
if (ds.Tables[0].Columns[0].ToString() == "ID" && ds.Tables[0].Columns[1].ToString() == "name")
{
}
//else if (ds.Tables[0].Rows[0][i].ToString().ToUpper() == "NAME")
//{
//}
//else if (ds.Tables[0].Rows[0][i].ToString().ToUpper() == "EMAIL")
//{
//}
}
}
//set data source of the grid view
gvExcelFile.DataSource = ds.Tables[0];
//binding the gridview
gvExcelFile.DataBind();
//close the connection
conn.Close();
}
}
}
try
{
System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName("Excel");
foreach (System.Diagnostics.Process p in process)
{
if (!string.IsNullOrEmpty(p.ProcessName))
{
try
{
p.Kill();
}
catch { }
}
}
REF_User oREF_User = new REF_User();
oREF_User = (REF_User)Session["LoggedUser"];
string pdfFilePath = Server.MapPath("~/FileUpload/" + oREF_User.USER_ID + "");
if (Directory.Exists(pdfFilePath))
{
System.IO.DirectoryInfo di = new DirectoryInfo(pdfFilePath);
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
Directory.Delete(pdfFilePath);
}
Directory.CreateDirectory(pdfFilePath);
string path = Server.MapPath("~/FileUpload/" + oREF_User.USER_ID + "/");
if (Path.GetExtension(FileUpload1.FileName) == ".xlsx")
{
string fullpath1 = path + Path.GetFileName(FileUpload1.FileName);
if (FileUpload1.FileName != "")
{
FileUpload1.SaveAs(fullpath1);
}
FileStream Stream = new FileStream(fullpath1, FileMode.Open);
IExcelDataReader ExcelReader = ExcelReaderFactory.CreateOpenXmlReader(Stream);
DataSet oDataSet = ExcelReader.AsDataSet();
Stream.Close();
bool result = false;
foreach (System.Data.DataTable oDataTable in oDataSet.Tables)
{
//ToDO code
}
oBL_PlantTransactions.InsertList(oListREF_PlantTransactions, null);
ShowMessage("Successfully saved!", REF_ENUM.MessageType.Success);
}
else
{
ShowMessage("File Format Incorrect", REF_ENUM.MessageType.Error);
}
}
catch (Exception ex)
{
ShowMessage("Please check the details and submit again!", REF_ENUM.MessageType.Error);
System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName("Excel");
foreach (System.Diagnostics.Process p in process)
{
if (!string.IsNullOrEmpty(p.ProcessName))
{
try
{
p.Kill();
}
catch { }
}
}
}
I found this article to be very helpful.
It lists various libraries you can choose from. One of the libraries I used is EPPlus as shown below.
Nuget: EPPlus Library
Excel Sheet 1 Data
Cell A2 Value :
Cell A2 Color :
Cell B2 Formula :
Cell B2 Value :
Cell B2 Border :
Excel Sheet 2 Data
Cell A2 Formula :
Cell A2 Value :
static void Main(string[] args)
{
using(var package = new ExcelPackage(new FileInfo("Book.xlsx")))
{
var firstSheet = package.Workbook.Worksheets["First Sheet"];
Console.WriteLine("Sheet 1 Data");
Console.WriteLine($"Cell A2 Value : {firstSheet.Cells["A2"].Text}");
Console.WriteLine($"Cell A2 Color : {firstSheet.Cells["A2"].Style.Font.Color.LookupColor()}");
Console.WriteLine($"Cell B2 Formula : {firstSheet.Cells["B2"].Formula}");
Console.WriteLine($"Cell B2 Value : {firstSheet.Cells["B2"].Text}");
Console.WriteLine($"Cell B2 Border : {firstSheet.Cells["B2"].Style.Border.Top.Style}");
Console.WriteLine("");
var secondSheet = package.Workbook.Worksheets["Second Sheet"];
Console.WriteLine($"Sheet 2 Data");
Console.WriteLine($"Cell A2 Formula : {secondSheet.Cells["A2"].Formula}");
Console.WriteLine($"Cell A2 Value : {secondSheet.Cells["A2"].Text}");
}
}

Object reference not set to instance of object when parsing excel spreadsheet

I wrote my own import from excel method for an excel sheet my company uses to show the budgets for the different departments in the store. All I cared about from the sheet were the two columns related to date and the budget for our department.
public static string[][] ImportBudgets(string filename)
{
var xlApp = new Application();
var xlWorkBook = xlApp.Workbooks.Open(filename, 0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
var xlWorkSheet = (Worksheet)xlWorkBook.Worksheets.Item[1];
var range = xlWorkSheet.UsedRange;
var budgetsArray = new string[range.Rows.Count][];
// loop through excel spreadsheet and get data
for (var rCnt = 3; rCnt <= range.Rows.Count; rCnt++)
{
var budgetDate = (string)((Range)range.Cells[rCnt, 1]).Value2;
var budgetAmount = (decimal)((Range)range.Cells[rCnt, 8]).Value2;
budgetsArray[rCnt - 3] = new[] { budgetDate, budgetAmount.ToString(CultureInfo.CurrentCulture) };
}
// cleanup
xlWorkBook.Close(true, null, null);
xlApp.Quit();
Marshal.ReleaseComObject(xlWorkSheet);
Marshal.ReleaseComObject(xlWorkBook);
Marshal.ReleaseComObject(xlApp);
return budgetsArray;
}
public string ImportBudgets(string filename)
{
try
{
// get dates and budgets from excel in array
var budgets = CExcel.ImportBudgets(filename);
using (var oDc = new StatTrackerTablesDataContext())
{
foreach (var innerArray in budgets)
{
var budget = new tblBudget();
DateTime budgetdate;
if (DateTime.TryParse(innerArray[0], out budgetdate) != true) continue;
budget.Budget_ID = Guid.NewGuid();
budget.Budget_Date = budgetdate;
budget.Budget_Amount = decimal.Parse(innerArray[1]);
budget.Budget_Goal = decimal.Parse(innerArray[1]) * (decimal)1.1;
oDc.tblBudgets.InsertOnSubmit(budget);
oDc.SubmitChanges();
}
}
return "Budgets imported without problems.";
}
catch (SqlException ex)
{
if (ex.Number == 2627)
{
return "Budget already existed for a date in batch. Import aborted.";
}
else
{
return ex.Message;
}
}
catch (Exception ex)
{
if (ex.Message.Contains("Object reference not set to an instance of an object."))
return "Budgets imported without problems.";
return ex.Message;
}
}
The import will run and import all of the dates and budgets properly but will always have null objects after getting to the row after the last one populated properly. I threw in the error handling for the object reference message, but it's obviously not a good tactic if there really is an issue with the import process. I was just seeing if anyone could help me refine it to prevent the message from occurring.
Alright, I hadn't visited this code in a while because it did get the job done. It was just the workaround that I didn't like being in there to avoid an error message. I noticed that I dimensioned the array for the entire row count of the excel document, but the document contained rows that weren't parsed for budgets because they weren't actual dates. There were 2-3 rows per document that get skipped because the "date" column says something like "Week 2". This resulted in the budgets array having 2-3 null innerArrays and my secondary budget import method would try and parse the null arrays. I thought the code:
if (DateTime.TryParse(innerArray[0], out budgetdate) != true) continue;
Would have kept the array from being parsed, but ignored the fact that the exception will be thrown before returning false. I just added
if (innerArray == null) continue;
at the beginning of the foreach loop and now it imports without needing the
catch (Exception ex)
{
if (ex.Message.Contains("Object reference not set to an instance of an object."))
return "Budgets imported without problems.";
return ex.Message;
}

Error making more than one copy of OpenXML worksheet

I have a program which modifies an existing spreadsheet. Part of the program creates copies of certain sheets. To create one copy, the program runs perfectly and the resulting file is also fine, presenting no errors when opened in Excel. However, when creating two copies of the same worksheet, the program still runs just fine but, when opened in Excel, the following error appears regarding unreadable content:
Repaired Records: Worksheet properties from /xl/workbook.xml part (Workbook)
Here is the code used to perform the copy:
private void CopySheet(int sNum, int pNum, string type)
{
var tempSheet = SpreadsheetDocument.Create(new MemoryStream(), SpreadsheetDocumentType.Workbook);
WorkbookPart tempWBP = tempSheet.AddWorkbookPart();
var part = Document.XGetWorkSheetPart(sNum);
var sheetData = part.Worksheet.ChildElements[5].Clone() as SheetData;
var merge = part.Worksheet.ChildElements[6].Clone() as MergeCells;
WorksheetPart tempWSP = tempWBP.AddPart<WorksheetPart>(part);
var copy = Document.WorkbookPart.AddPart<WorksheetPart>(tempWSP);
//copy.Worksheet.RemoveChild<SheetData>(copy.Worksheet.ChildElements[5] as SheetData);
//copy.Worksheet.InsertAt<SheetData>(sheetData, 5);
//copy.Worksheet.RemoveChild<MergeCells>(copy.Worksheet.ChildElements[6] as MergeCells);
//copy.Worksheet.InsertAt<MergeCells>(merge, 6);
//copy.Worksheet.SheetProperties.CodeName.Value = "Phase" + pNum + type;
var sheets = Document.WorkbookPart.Workbook.Sheets;
var sheet = new Sheet();
sheet.Id = Document.WorkbookPart.GetIdOfPart(copy);
sheet.Name = "Phase " + pNum + " " + type;
sheet.SheetId = (uint)sheets.ChildElements.Count;
sheets.Append(sheet);
}
This method makes use of the fact that .AddPart<>() performs a deep copy of any Part (and anything it references to) which does not already belong in the document to, with the help of a temporary sheet, create a deep copy of all referenced parts of a WorkSheet.
As stated above, this works quite well if the function is called only once for a given sheet. If it is called more than once, however, the file when opened in Excel gives an error of unreadable content. That being said, the file itself seems just fine, with no missing data or anything (which would help to figure out what exactly was wrong), just the error saying there was something wrong.
The lines that are commented out are a "hack" I had to do to deal with problems regarding .AddPart<>(), but I won't go into much detail with them here because I've already posted about this here (but I still haven't gotten a reply, so by all means, please answer that question, too!). That being said, those lines seem to have no relevance to this current problem since the error appears with or without those lines of code.
I noticed the source file's sheets were not numbered properly for whatever reason, so their SheetID's were not sequencial (6, 1, 3). Therefore, my program was, when creating two copies of the file with the code sheet.SheetID = sheets.ChildElements.Count + 1, setting the values as 4, 5, 6 and 7, which lead to a conflict with the existing sheets. I've therefore modified that section so that the program always gets a valid ID:
// ...
uint id = 1;
bool valid = false;
while (!valid)
{
uint temp = id;
foreach (OpenXmlElement e in sheets.ChildElements)
{
var s = e as Sheet;
if (id == s.SheetId.Value)
{
id++;
break;
}
}
if (temp == id)
valid = true;
}
sheet.SheetId = id;
//...
With this my sheetIDs become (6, 1, 3, 2, 4, 5, 7), and therefore there are no conflicts and no more errors!
static WorksheetPart GetWorkSheetPart(WorkbookPart workbookPart, string sheetName)
{
//Get the relationship id of the sheetname
string relId = workbookPart.Workbook.Descendants<Sheet>()
.Where(s => s.Name.Value.Equals(sheetName))
.First()
.Id;
return (WorksheetPart)workbookPart.GetPartById(relId);
}
static void FixupTableParts(WorksheetPart worksheetPart, int numTableDefParts)
{
//Every table needs a unique id and name
foreach (TableDefinitionPart tableDefPart in worksheetPart.TableDefinitionParts)
{
tableId++;
tableDefPart.Table.Id = (uint)tableId;
tableDefPart.Table.DisplayName = "CopiedTable" + tableId;
tableDefPart.Table.Name = "CopiedTable" + tableId;
tableDefPart.Table.Save();
}
}
private void CopySheet(SpreadsheetDocument mySpreadsheet, string sheetName, string clonedSheetName)
{
WorkbookPart workbookPart = mySpreadsheet.WorkbookPart;
IEnumerable<Sheet> source = workbookPart.Workbook.Descendants<Sheet>();
Sheet sheet = Enumerable.First<Sheet>(source, (Func<Sheet, bool>)(s => (string)s.Name == sheetName));
string sheetWorkbookPartId = (string)sheet.Id;
WorksheetPart sourceSheetPart = (WorksheetPart)workbookPart.GetPartById(sheetWorkbookPartId);
SpreadsheetDocument tempSheet = SpreadsheetDocument.Create(new MemoryStream(), mySpreadsheet.DocumentType);
WorkbookPart tempWorkbookPart = tempSheet.AddWorkbookPart();
WorksheetPart tempWorksheetPart = tempWorkbookPart.AddPart<WorksheetPart>(sourceSheetPart);
//Add cloned sheet and all associated parts to workbook
WorksheetPart clonedSheet = workbookPart.AddPart<WorksheetPart>(tempWorksheetPart);
int numTableDefParts = sourceSheetPart.GetPartsCountOfType<TableDefinitionPart>();
tableId = numTableDefParts;
if (numTableDefParts != 0)
FixupTableParts(clonedSheet, numTableDefParts);
CleanView(clonedSheet);
//Add new sheet to main workbook part
Sheets sheets = workbookPart.Workbook.GetFirstChild<Sheets>();
Sheet copiedSheet = new Sheet();
copiedSheet.Name = clonedSheetName;
copiedSheet.Id = workbookPart.GetIdOfPart(clonedSheet);
copiedSheet.SheetId = (uint)sheets.ChildElements.Count + 1;
sheets.Append(copiedSheet);
workbookPart.Workbook.Save();
}
static void CleanView(WorksheetPart worksheetPart)
{
SheetViews views = worksheetPart.Worksheet.GetFirstChild<SheetViews>();
if (views != null)
{
views.Remove();
worksheetPart.Worksheet.Save();
}
}

Categories

Resources