Error making more than one copy of OpenXML worksheet - c#

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();
}
}

Related

Loading tsv/csv file in excel sheet

This is my code.
public static string LoadPackage(DirectoryInfo outputDir, string name)
{
FileInfo newFile = new FileInfo(outputDir.FullName + #"\test.xlsx");
if (newFile.Exists)
{
newFile.Delete();
newFile = new FileInfo(outputDir.FullName + #"\test.xlsx");
}
var format = new ExcelTextFormat();
format.Delimiter = '\t';
format.SkipLinesBeginning = 1;
using (ExcelPackage package = new ExcelPackage())
{
LoadSheet(package, outputDir, name);
package.SaveAs(newFile);
}
return newFile.FullName;
}
And after that i call LoadSheet method in order to fill my excel file from tsv file.
public static void LoadSheet(ExcelPackage package, DirectoryInfo
outputDir, string name)
{
var ws = package.Workbook.Worksheets.Add("Content");
var format = new ExcelTextFormat();
format.Delimiter = '\t';
format.SkipLinesBeginning = 2;
format.SkipLinesEnd = 1;
var range = ws.Cells["A1"].LoadFromText(new
FileInfo(outputDir.FullName + "\\" + name), format,
TableStyles.Medium27, false);
}
And this is my code on button click event
if (BrowseFileUpload.HasFile)
{
var name = BrowseFileUpload.PostedFile.FileName;
InputTextBox.Text = name;
LoadData.LoadPackage(new
System.IO.DirectoryInfo("C:\\Users\\Nemanja\\Downloads"), name);
InfoLabel.Text = "Your data has been imported!!!";
InfoLabel.ForeColor = System.Drawing.Color.Blue;
InfoLabel.Font.Size = 20;
}
Everything is ok i create new excel file, sheet save it but it does not load data that i need it to load inside excel file. It's only empty file or i get a error the file is corrupted recover what you can.
Can someone figure out what can be a problem based on my explanation and this code. Thank you all good people.
I think that the problem may well be with the format of your source data. I've put together the following sample, based on your code, and it works fine.
var outFile = Path.ChangeExtension(filePath, ".xlsx");
using (var p = new ExcelPackage())
{
var fmt = new ExcelTextFormat();
fmt.Delimiter = '\t';
fmt.SkipLinesBeginning = 2;
fmt.SkipLinesEnd = 1;
fmt.EOL = ((char)10).ToString(); // THIS LINE FIXED THE PROBLEM (UNIX NEWLINE)
var ws = p.Workbook.Worksheets.Add("Imported Text");
ws.Cells[1, 1].LoadFromText(new FileInfo(filePath), fmt, TableStyles.Medium27, false);
p.SaveAs(new FileInfo(outFile));
}
Try running your data through this and see if you get the same issue or not.
UPDATED
The problem was a unix-style newline in the file - EPPlus expects a windows-style newline by default

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.

EPPlus with a template is not working as expected

I am currently using EPPlus project in order to manipulate some .xlsx files. The basic idea is that I have to create a new file from a given template.
But when I create the new file from a template, all calculated columns in the tables are messed up.
The code I am using is the following:
static void Main(string[] args)
{
const string templatePath = "template_worksheet.xlsx"; // the path of the template
const string resultPath = "result.xlsx"; // the path of our result
using (var pck = new ExcelPackage(new FileInfo(resultPath), new FileInfo(templatePath))) // creating a package with the given template, and our result as the new stream
{
// note that I am not doing any work ...
pck.Save(); // savin our work
}
}
For example for a .xlsx file (that have a table with 3 columns, the last one is just the sum of the others) the program creates a .xlsx file where the last column have the same value (which is correct only for the first row) in all rows.
The following images shows the result:
Now the questions are:
What is going on here ? Is my code wrong ?
How can I accomplish this task without that unexpected behavior ?
That definitely on to something there. I was able to reproduce it myself. It has to do with the Table you created. if you open your file and remove it using the "Convert To Range" option in the Table Tools tab the problem goes away.
I looked at the source code and it extracts the xml files at the zip level and didnt see any indication that it was actually messing with them - seemed to be a straight copy.
Very strange because if we create and save the xlsx file including a table from EPPlus the problem is not there. This works just fine:
[TestMethod]
public void Template_Copy_Test()
{
//http://stackoverflow.com/questions/28722945/epplus-with-a-template-is-not-working-as-expected
const string templatePath = "c:\\temp\\testtemplate.xlsx"; // the path of the template
const string resultPath = "c:\\temp\\result.xlsx"; // the path of our result
//Throw in some data
var dtdata = new DataTable("tblData");
dtdata.Columns.Add(new DataColumn("Col1", typeof(string)));
dtdata.Columns.Add(new DataColumn("Col2", typeof(int)));
dtdata.Columns.Add(new DataColumn("Col3", typeof(int)));
for (var i = 0; i < 20; i++)
{
var row = dtdata.NewRow();
row["Col1"] = "String Data " + i;
row["Col2"] = i * 10;
row["Col3"] = i * 100;
dtdata.Rows.Add(row);
}
var templateFile = new FileInfo(templatePath);
if (templateFile.Exists)
templateFile.Delete();
using (var pck = new ExcelPackage(templateFile))
{
var ws = pck.Workbook.Worksheets.Add("Data");
ws.Cells["A1"].LoadFromDataTable(dtdata, true);
for (var i = 2; i <= dtdata.Rows.Count + 1; i++)
ws.Cells[i, 4].Formula = String.Format("{0}*{1}", ExcelCellBase.GetAddress(i, 2), ExcelCellBase.GetAddress(i, 3));
ws.Tables.Add(ws.Cells[1, 1, dtdata.Rows.Count + 1, 4], "TestTable");
pck.Save();
}
using (var pck = new ExcelPackage(new FileInfo(resultPath), templateFile)) // creating a package with the given template, and our result as the new stream
{
// note that I am not doing any work ...
pck.Save(); // savin our work
}
}
BUT.....
If we open testtemplate.xlsx, remove the table, save/close the file, reopen, and reinsert the exact same table the problem shows up when you run this:
[TestMethod]
public void Template_Copy_Test2()
{
//http://stackoverflow.com/questions/28722945/epplus-with-a-template-is-not-working-as-expected
const string templatePath = "c:\\temp\\testtemplate.xlsx"; // the path of the template
const string resultPath = "c:\\temp\\result.xlsx"; // the path of our result
var templateFile = new FileInfo(templatePath);
using (var pck = new ExcelPackage(new FileInfo(resultPath), templateFile)) // creating a package with the given template, and our result as the new stream
{
// note that I am not doing any work ...
pck.Save(); // savin our work
}
}
It has to be something burried in their zip copy methods but I nothing jumped out at me.
But at least you can see about working around it.
Ernie
Try to use the following code. This code takes the formatting and other rules and add them as xml node to another file. Ernie described it really well here Importing excel file with all the conditional formatting rules to epplus The best part of the solution is that you can also import formatting along with your other rules. It should take you close to what you need.
//File with your rules, can be your template
var existingFile = new FileInfo(#"c:\temp\temp.xlsx");
//Other file where you want the rules
var existingFile2 = new FileInfo(#"c:\temp\temp2.xlsx");
using (var package = new ExcelPackage(existingFile))
using (var package2 = new ExcelPackage(existingFile2))
{
//Make sure there are document element for the source
var worksheet = package.Workbook.Worksheets.First();
var xdoc = worksheet.WorksheetXml;
if (xdoc.DocumentElement == null)
return;
//Make sure there are document element for the destination
var worksheet2 = package2.Workbook.Worksheets.First();
var xdoc2 = worksheet2.WorksheetXml;
if (xdoc2.DocumentElement == null)
return;
//get the extension list node 'extLst' from the ws with the formatting
var extensionlistnode = xdoc
.DocumentElement
.GetElementsByTagName("extLst")[0];
//Create the import node and append it to the end of the xml document
var newnode = xdoc2.ImportNode(extensionlistnode, true);
xdoc2.LastChild.AppendChild(newnode);
package2.Save();
}
}
Try this
var package = new ExcelPackage(excelFile)
var excelSheet = package.Workbook.Worksheets[1];
for (var i = 1; i < 5; i++){
excelWorkSheet.InsertRow(i, 1, 1); // Use value of i or whatever is suitable for you
}
package.Workbook.Calculate();
Inserting new row copies previous row format and its formula if last prm is set to 1

This command requires at least two rows of source data

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.

export data to excel file in an asp.net application

Can someone provide a link with a tutorial about exporting data to an excel file using c# in an asp.net web application.I searched the internet but I didn't find any tutorials that will explain how they do it.
You can use Interop http://www.c-sharpcorner.com/UploadFile/Globalking/datasettoexcel02272006232336PM/datasettoexcel.aspx
Or if you don't want to install Microsoft Office on a webserver
I recommend using CarlosAg.ExcelXmlWriter which can be found here: http://www.carlosag.net/tools/excelxmlwriter/
code sample for ExcelXmlWriter:
using CarlosAg.ExcelXmlWriter;
class TestApp {
static void Main(string[] args) {
Workbook book = new Workbook();
Worksheet sheet = book.Worksheets.Add("Sample");
WorksheetRow row = sheet.Table.Rows.Add();
row.Cells.Add("Hello World");
book.Save(#"c:\test.xls");
}
}
There is a easy way to use npoi.mapper with just below 2 lines
var mapper = new Mapper();
mapper.Save("test.xlsx", objects, "newSheet");
Pass List to below method, that will convert the list to buffer and then return buffer, a file will be downloaded.
List<T> resultList = New List<T>();
byte[] buffer = Write(resultList, true, "AttendenceSummary");
return File(buffer, "application/excel", reportTitle + ".xlsx");
public static byte[] Write<T>(IEnumerable<T> list, bool xlsxExtension = true, string sheetName = "ExportData")
{
if (list == null)
{
throw new ArgumentNullException("list");
}
XSSFWorkbook hssfworkbook = new XSSFWorkbook();
int Rowspersheet = 15000;
int TotalRows = list.Count();
int TotalSheets = TotalRows / Rowspersheet;
for (int i = 0; i <= TotalSheets; i++)
{
ISheet sheet1 = hssfworkbook.CreateSheet(sheetName + "_" + i);
IRow row = sheet1.CreateRow(0);
int index = 0;
foreach (PropertyInfo property in typeof(T).GetProperties())
{
ICellStyle cellStyle = hssfworkbook.CreateCellStyle();
IFont cellFont = hssfworkbook.CreateFont();
cellFont.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
cellStyle.SetFont(cellFont);
ICell cell = row.CreateCell(index++);
cell.CellStyle = cellStyle;
cell.SetCellValue(property.Name);
}
int rowIndex = 1;
// int rowIndex2 = 1;
foreach (T obj in list.Skip(Rowspersheet * i).Take(Rowspersheet))
{
row = sheet1.CreateRow(rowIndex++);
index = 0;
foreach (PropertyInfo property in typeof(T).GetProperties())
{
ICell cell = row.CreateCell(index++);
cell.SetCellValue(Convert.ToString(property.GetValue(obj)));
}
}
}
MemoryStream file = new MemoryStream();
hssfworkbook.Write(file);
return file.ToArray();
}
You can try the following links :
http://www.codeproject.com/Articles/164582/8-Solutions-to-Export-Data-to-Excel-for-ASP-NET
Export data as Excel file from ASP.NET
http://codeissue.com/issues/i14e20993075634/how-to-export-gridview-control-data-to-excel-file-using-asp-net
I've written a C# class, which lets you write your DataSet, DataTable or List<> data directly into a Excel .xlsx file using the OpenXML libraries.
http://mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm
It's completely free to download, and very ASP.Net friendly.
Just pass my C# function the data to be written, the name of the file you want to create, and your page's "Response" variable, and it'll create the Excel file for you, and write it straight to the Page, ready for the user to Save/Open.
class Employee;
List<Employee> listOfEmployees = new List<Employee>();
// The following ASP.Net code gets run when I click on my "Export to Excel" button.
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
// It doesn't get much easier than this...
CreateExcelFile.CreateExcelDocument(listOfEmployees, "Employees.xlsx", Response);
}
(I work for a finanical company, and we'd be lost without this functionality in every one of our apps !!)

Categories

Resources