How to create a custom job to export an Excel file in a list which has only 2 columns(Title,Description) in a sharepoint 2010?i want the coding part of this question?
Reading Data from Excel and writing into a sharepoint list,this has to be done through custom job coding
Thanks in Advance...
Naresh
Use OpenXMLSDK - a free download that needs to be installed on the server.
[...]
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
public class OffBookAssetLibraryEventReceiver : SPItemEventReceiver
{
public override void ItemUpdated(SPItemEventProperties properties)
{
// This if statement is to work around the sharepoint issue of this event firing twice.
if (properties.AfterProperties["vti_sourcecontrolcheckedoutby"] == null && properties.BeforeProperties["vti_sourcecontrolcheckedoutby"] != null)
{
byte[] workSheetByteArray = properties.ListItem.File.OpenBinary();
Stream stream = new MemoryStream(workSheetByteArray);
Package spreadsheetPackage = Package.Open(stream, FileMode.Open, FileAccess.ReadWrite);
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(spreadsheetPackage);
SharedStringTablePart shareStringTablePart = spreadsheetDocument.WorkbookPart.SharedStringTablePart;
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.Sheets;
try
{
foreach (Sheet sheet in sheets)
{
var worksheetPart = (WorksheetPart)spreadsheetDocument.WorkbookPart.GetPartById(sheet.Id.Value);
IEnumerable<Row> rows = worksheetPart.Worksheet.GetFirstChild<SheetData>().Elements<Row>();
if (rows.Count() > 0)
{
int rowNumber = 0;
foreach (Row row in rows)
{
IEnumerable<Cell> cells = row.Elements<Cell>();
Cell title = null;
Cell description = null;
title = cells.ToArray()[0];
description = cells.ToArray()[1];
// This is the code used to extract cells from excel that are NOT inline (Inline cells are decimal and dates - although dates are stored as int)
int index = int.Parse(title.CellValue.Text);
string titleString = spreadsheetDocument.WorkbookPart.SharedStringTablePart.SharedStringTable.Elements<SharedStringItem>().ElementAt(index).InnerText;
index = int.Parse(description.CellValue.Text);
string descriptionString = spreadsheetDocument.WorkbookPart.SharedStringTablePart.SharedStringTable.Elements<SharedStringItem>().ElementAt(index).InnerText;
//Insert into your sharepoint list here!
}
}
}
}
}
}
}
I recommend putting this code into an event receiver on the document library (as seen above).
Have you looked at Excel REader for .NET
http://exceldatareader.codeplex.com/
Open the Excel File
Take a look at the Excel Services for SharePoint 2010. There is a walkthrough explaining the required steps to open an excel file.
SharePoint Custom Timer Job
To create a custom SharePoint timer job, you have to create a class that inherits from SPJobDefinition. A complete tutorial can be found in this blog post: Creating Custom Timer Job in SharePoint 2010.
Related
I'm working on a simple Outlook 2016/2019 VSTO plugin.
When an email is selected and a ribbon button is pressed, it needs to print just the first page of the email to the default printer. mailitem.PrintOut(); works, but will print the whole email. Is there a way to specify the first page only?
var m = e.Control.Context as Inspector;
var mailitem = m.CurrentItem as MailItem;
if (mailitem != null)
{
mailitem.PrintOut();
}
Update: See my answer for the code I used to get this working.
The Outlook object model doesn't provide any property or method for that. You need to parse the message body on your own and use .net mechanisms for printing this piece on your own.
Note, you may try using the Word object model for printing the message bodies (a specific range of pages). The Document.PrintOut method prints all or part of the specified document. Optional parameters allow specifying the page range.
The Outlook object model provides three main ways for working with item bodies:
Body - a string representing the clear-text body of the Outlook item.
HTMLBody - a string representing the HTML body of the specified item.
Word editor - the Microsoft Word Document Object Model of the message being displayed. The WordEditor property of the Inspector class returns an instance of the Document class from the Word object model which you can use to deal with the message body.
You can read more about all these ways in the Chapter 17: Working with Item Bodies.
As #Eugene said, there's no way to specify a single page using mailItem.PrintOut.
I've finally managed to find a way to do this. I save the document as a .doc file in the temp directory, then using Microsoft.Office.Interop.Word to setup the page margins / size and then send the current page to the printer. Hopefully this helps someone as I couldn't find any working examples for c#!
private void btnPrintOnePage_Click(object sender, RibbonControlEventArgs e)
{
string randFile = Path.GetTempPath() + "POP_" + RandomString(35) + ".doc";
var m = e.Control.Context as Inspector;
var mailitem = m.CurrentItem as MailItem;
if (mailitem != null)
{
mailitem.SaveAs(randFile, OlSaveAsType.olDoc);
Word.Application ap = new Word.Application();
Word.Document document = ap.Documents.Open(randFile);
document.PageSetup.PaperSize = Word.WdPaperSize.wdPaperA4;
document.PageSetup.TopMargin = 25;
document.PageSetup.RightMargin = 25;
document.PageSetup.BottomMargin = 25;
document.PageSetup.LeftMargin = 25;
Word.WdPrintOutRange printRange = Word.WdPrintOutRange.wdPrintCurrentPage;
document.PrintOut(false,null,printRange);
document.Close(false, false, false);
File.Delete(randFile);
}
}
public static string RandomString(int length)
{
Random random = new Random();
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
I am interested in using EPPlus for generating some xslx report files for a system. I'm interested in whether or not it is possible for EPPlus to tap into Excel's Equation's feature. This is different from formula's. I am aware of EPPlus's ability to add formula's and that's a great feature I am also using. The Equation feature in Excel prints out equations in a nice looking format and I am interested in using that in files I generate with EPPlus.
public ActionResult OnPostDownloadExcelFile()
{
var ms = new MemoryStream();
using (var package = new OfficeOpenXml.ExcelPackage(ms))
{
package.Workbook.Properties.Title = "Excel file with an equation in it";
// Worksheet
var worksheet = package.Workbook.Worksheets.Add("Report");
worksheet.View.ShowGridLines = true;
int row = 1;
int col = 1;
worksheet.Cells[row, col].Value = "I want to put an equation here...";
}
return File(ms, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "ExcelFileExample.xlsx");
}
Unfortunately this is not supported in EPPlus. Equations are an embedded object. Embedded objects are not presently supported: https://github.com/JanKallman/EPPlus/wiki/FAQ#what-is-not-supported-by-the-library-these-are-the-most-obvious-features
I haven't read enough theory or have had enough practice in CS, but there must be a simpler, faster way to look up data from a file. I'm working with a literal, real world dictionary .csv file, and I'm wondering how I can speed up look up of every word. No doubt going through the whole list for the word does not make sense; splitting the file into a-z order, and only looking there for each word, makes sense.
But what else? Should I learn SQL or something and try to convert the text database into an SQL database? Are there methods in SQL that would enable me to do what I wish? Please give me ideas!
SQLite sounds fit to this task.
Create a table, import your csv file, create an index and you're done.
I just did this using interop with a moderate size .csv file given me by a supply company. It worked well, but still requires a considerable delay due to the cumbersome decorators used in interop/COM.
class Excel
{
private excel.Application application;
private excel.Workbook excelWorkBook;
protected const string WORD_POSITION = "A"; //whichever column the word is located in when loaded on Excel spreadsheet.
protected const string DEFINITION_POSITION = "B"; // whichever column the definition is loaded into on Excel spreadsheet.
Dictionary<string,string> myDictionary = new Dicationary<string,string>();
public Excel(string path) // where path is the fileName
{
try
{
application = new excel.Application();
excelWorkBook = application.Workbooks.Add(path);
int row = 1;
while (application.Cells[++row, WORD_POSITION].Value != null)
{
myDictionary[GetValue(row, WORD_POSITION)] = GetValue(row, DEFINITION_POSITION);
});
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
finally
{
excelWorkBook.Close();
application.Quit();
}
}
private string GetValue(int row, string columnName)
{
string returnValue = String.Empty;
returnValue = application.Cells[row, columnName].Value2;
if (returnValue == null) return string.Empty;
return returnValue;
}
}
}
Create a new sql database, import the cab into a new table, place an index on the column that stores the word values, then search against table... That is the approach I would take
I have to add a choice field (dropdown) to a sharepoint list. I'm using the SharePoint API in Visual Studio.
Here is me code. I have tried to run this and there are no errors but it doesn't work.
private void addChoiceField(SPFeatureReceiverProperties properties, String _listName, String _fieldName)
{
using (SPWeb _web = properties.Feature.Parent as SPWeb)
{
SPList _list = _web.Lists.TryGetList(_listName);
writeLog(properties, "list name:" + _listName);
SPFieldChoice _fieldDD = (SPFieldChoice)_list.Fields[_fieldName];
writeLog(properties, "fieldname:" + _fieldName);
if (_fieldName == "State")
{
_fieldDD.Choices.Clear();
_fieldDD.Choices.Add("Gesloten-Verloren");
_fieldDD.Choices.Add("Analyse nodig");
_fieldDD.Choices.Add("Onderhandeling of revise");
_fieldDD.Choices.Add("Presentatie of demo");
_fieldDD.Choices.Add("Voorstel voor prijsofferte");
_fieldDD.Choices.Add("Prospect");
_fieldDD.Choices.Add("Waardevol");
_fieldDD.Choices.Add("Gesloten-Gewonnen");
_fieldDD.Update();
}
}
}
Does anyone knows what's wrong or how to add a choicefield in a different way using the API?
You need to call
_list.Fields.CreateNewField
to actually add it to the list instead of trying to pull an existing field from the list.
Here is a link to the method description: http://msdn.microsoft.com/en-us/library/microsoft.harepoint.spfieldcollection.createnewfield.aspx
I try update Extenal data column but it doesn't work, new value is not stored. (new value is visible on details form but not on list, rehreshing external data type does not return related external column values)
using (SPSite oSiteCollection = new SPSite("site.com"))
{
using (SPWeb oWebsite = oSiteCollection.OpenWeb("site.com"))
{
using (SPWeb oWebsiteRoot = oSiteCollection.RootWeb)
{
SPList docLib = oWebsiteRoot.Lists["list name"];
SPListItemCollection items = docLib.Items;
foreach (SPListItem item in items)
{
//item["n"] is external column data field
item["n"] = item["notice"].ToString();
item.UpdateOverwriteVersion();
}
}
}
}
Check using item.Update() insted of item.UpdateOverwriteVersion()
This has to do with the field type and is quite complicated to get right.
There is a free external data field migration/copy tool here:
http://rrfreeman.blogspot.com/2013/06/bcs-bdc-external-data-lookup-field.html
I included source code and links to relevant articles.