Code iS Poetry!
Currently viewing the category:
"C#"
This is a small function i wrote in C# to calculate the density of say twitter posts or events … it takes as a parameter a list of UNIX timestamps. It can be easily moddified to get a list of DateTime items.
private static DateTime ConvertFromUnixTimestamp(double timestamp)
{
DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
return origin.AddSeconds(timestamp);
}
public Dictionary<int, int> CalculateDensity(List<int> timestamps)
{
// the Key represents the hour ,
// and the value represents the number of timestamps sent during a given hour
var converted = new Dictionary<int, int>();
foreach (var stamp in timestamps)
{
var hour = ConvertFromUnixTimestamp(stamp);
if (converted.ContainsKey(hour.Hour))
{
converted[hour.Hour]++;
}
else
{
converted.Add(hour.Hour, 1);
}
}
return converted;
}
At work my boss asked me to automate some document creation form data in Excel and i said OK , even tho i havent ever done something like this.
After a couple of days of going trough the MSDN documentation and few google pages i finaly did it !
Here is the source with lots of comments , i hope its some use to you
Add references to MS interop word & excell
then
using Microsoft.Office.Interop.Word; using Word = Microsoft.Office.Interop.Word; using Excel = Microsoft.Office.Interop.Excel;
//defines new excel and workd apps
var ap = new Word.Application();
var excelApp = new Excel.Application();
// defines new excel worksheet & workbooks
Excel.Workbook exBook;
Excel.Worksheet xlWorkSheet;
// should the excell/word apps be visible ?
excelApp.Visible = false;
ap.Visible = false;
//defining the index numbers of our content controls that are in the word template
// index numbers start from 1 and are numbered by order of creation
object Price, Name, address;
Price = 1;
Name = 2;
address = 3;
// here we open the excell file
exBook = excelApp.Workbooks.Open(@"C:\test.xls");
// and we open the first worksheet
xlWorkSheet = exBook.Worksheets.get_Item(1);
Excel.Range range ;
//here we select the first worksheet and make it active
Excel._Worksheet workSheet = (Excel.Worksheet) excelApp.ActiveSheet;
//we open the word document
var doc = ap.Documents.Open(@"C:\test.dotx", ReadOnly: false, Visible: false);
// and we assign the content controls
var dPrice = doc.ContentControls.get_Item(ref Price);
var dName = doc.ContentControls.get_Item(ref Name);
var dAddress = doc.ContentControls.get_Item(ref address);
doc.Activate();
range = xlWorkSheet.UsedRange;
// here we define the columns that we are going to select
object t, P , E , K, N,M,J;
P = "P";
E = "E";
K = "K";
J = "J";
N = "N";
M = "M";
// and here we loop trought the rows of the excell worksheet
// IMPORTANT! excell rows count starts from 1 and not from 0 !
for (int i =1; i< Convert.ToInt16(Settings1.Default.copies) ;i++)
{
t = i;
// here we get the value if cell t(1..2..3..etc), P
var dummy = (range.Cells[t, P] as Excel.Range).Value2;
// here we insert the content of the cell to the content control
dPrice.Range.Text = ": " + Convert.ToString(dummy) + " лв";
dName.Range.Text = ": " + (string)(range.Cells[t, E] as Excel.Range).Value2;
// same thing here
var city = (string) (range.Cells[t, J] as Excel.Range).Value2;
var address1 = (string) (range.Cells[t, K] as Excel.Range).Value2;
try
{
//here we try to save the word document as a pdf file
object name = @"C:\t\test"+i+".pdf";
object FileFormat = WdSaveFormat.wdFormatPDF;
doc.SaveAs(ref name, ref FileFormat);
}
catch (Exception ex)
{
MessageBox.Show("Exception Caught: " + ex.Message +" source "+ ex.Source.ToString());
}
}
// here quit word without saving the changes to the template
ap.Quit(SaveChanges: false, OriginalFormat: false, RouteDocument: false);
excelApp.Quit();
// and we release the objects
System.Runtime.InteropServices.Marshal.ReleaseComObject(ap);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
Categories
- Google (3)
- infinity (1)
- ROFL (9)
- Shit i like! (18)
- Still Life (18)
- Uncategorized (2)
- web 3.0 (4)
- Социална медия (2)
- Wish List (2)
- Благинки (6)
- Изблици (5)
- Лични (9)
- Мисли (7)
- музика (15)
- Мюзик ланд (2)
- Опера (4)
- Пари от интернет (3)
- Програмиране (5)
- C# (2)
- Разни (22)
- Скукотрепач (16)
- Филмотека (10)
Последни коментари
Мои неща
Tags
C# edno23 FaceBook Google hip-hop ILLMATE love love story in pictures manifesto Manu Chao matrix me Micro23 Music Opera pronobozo Qlimax song sotry Still Life Мисли Опера Пари от интернет Песен Програмиране Скукотрепач въпроси живот интернет лудост любов миризма музика наркотици неща нов помощ смърт смях социална мрежа усмивки училище филм хора чорапи
live form edno23.com- aviatrix: малко четиво за хеширане на пароли:)
- aviatrix: мини edno23 Среща - Дата : 08.04 : Час :6:30 , място Дон Домат (виж линк) телефон за връзка ако не можете да ни откриете : 0883324129 http://bit.ly/IcFpMH
- aviatrix: #skypechats
- aviatrix: mind-blowing !
- aviatrix: Project Glass By Google , не е първоаприлска шега :)

