How to format cell with number using ClosedXML? - c#

by using following code I am only formatting the respective cell but while I am selecting the whole column it's showing the general format as label please see the attach imageenter image description here
enter image description here
var ws = wb.Worksheets.Add("Contacts");
//Adding text
//Title
ws.Cell("B2").Value = "Contacts";
//First Names
ws.Cell("B3").Value = "FName";
ws.Cell("B4").Value = "John";
ws.Cell("B5").Value = "Hank";
ws.Cell("B6").SetValue("Dagny"); // Another way to set the value
//Last Names
ws.Cell("C3").Value = "LName";
ws.Cell("C4").Value = "Galt";
ws.Cell("C5").Value = "Rearden";
ws.Cell("C6").SetValue("Taggart"); // Another way to set the value
//Adding more data types
//Is an outcast?
ws.Cell("D3").Value = "Outcast";
ws.Cell("D4").Value = true;
ws.Cell("D5").Value = false;
ws.Cell("D6").SetValue(false); // Another way to set the value
//Date of Birth
ws.Cell("E3").Value = "DOB";
ws.Cell("E4").Value = new DateTime(1919, 1, 21);
ws.Cell("E5").Value = new DateTime(1907, 3, 4);
ws.Cell("E6").SetValue(new DateTime(1921, 12, 15)); // Another way to set the value
//Income
ws.Cell("F3").Value = "Income";
ws.Cell("F4").Value = 2000;
ws.Cell("F5").Value = 40000;
ws.Cell("F6").SetValue(10000); // Another way to set the value
//Defining ranges
//From worksheet
var rngTable = ws.Range("B2:F6");
//From another range
var rngDates = rngTable.Range("D3:D5"); // The address is relative to rngTable (NOT the worksheet)
var rngNumbers = rngTable.Range("E3:E5"); // The address is relative to rngTable (NOT the worksheet)
//Formatting dates and numbers
//Using a OpenXML's predefined formats
rngDates.Style.NumberFormat.NumberFormatId = 15;
//Using a custom format
rngNumbers.Style.NumberFormat.Format = "$ #,##0";

Related

fill chart from csv file

I have csv file with data:
1,1671790171,75
0,1671790182,11
1,1671790193,11
0,1671790212,19
1,1671790239,27
0,1671790248,97
1,1671790342,94
0,1671790361,19
1,1671790368,79
0,1671790408,40
1,1671790417,90
0,1671790432,15
I need create application to show chart where first data is "work" or "not work", second data is linuxtimestamp data and time, third data is the number of seconds the process took.
I wrote something like this:
// Use OpenFileDialog to allow the user to select a CSV file
var openFileDialog = new OpenFileDialog
{
Filter = "CSV files (*.csv)|*.csv"
};
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
// Clear the chart
chart1.Series.Clear();
// Read the CSV file
using (var reader = new StreamReader(openFileDialog.FileName))
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
// Parse the values
var working = values[0] == "1";
var timestamp = long.Parse(values[1]);
var duration = int.Parse(values[2]);
// Convert the Unix timestamp to a DateTime
var date = DateTimeOffset.FromUnixTimeSeconds(timestamp).UtcDateTime;
// Create a new series in the chart
var series = new System.Windows.Forms.DataVisualization.Charting.Series
{
Name = date.ToString("dd-MM-yyyy HH:mm:ss"),
Color = working ? Color.Red : Color.Green,
BorderColor = Color.Black,
ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Bar,
IsXValueIndexed = false,
XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.DateTime
};
series.Points.AddXY(date, duration);
chart1.Series.Add(series);
}
}
// Set the bar width for all series
foreach (var series in chart1.Series)
{
foreach (var point in series.Points)
{
// point.Width = 20;
point.BorderWidth = 0;
}
}
However, I need help with replacing so that on line X there are all occurrences (i.e. each line) with preferably a vertical entry of the date of occurrence, and on line Y there is time of operation (i.e. the last data from each line)

How to add multiple texts on Visio connector shapes using the c#/vba code?

I want to add multiple texts on the connector line as per the image below. I am using c# code to automate the process. Below is my code which I have used. It is not giving the exact output as I had expected. Any help in this regard would be highly appreciated.
Visio.Shape vsoLastShape = visioPage.Shapes.get_ItemFromID(lastshapeID);
vsoLastShape.ConvertToGroup();
Visio.Selection vsoSelections = app.ActiveWindow.Selection;
vsoSelections.Select(vsoLastShape, (short)VisSelectArgs.visSelect);
Visio.Shape vsoGroupShape = vsoSelections.Group();
vsoGroupShape.Text = "Testing 12";
vsoGroupShape.TextStyle.PadLeft(10);
Whatever method (manual, C#, VBA or whatevber) you use, one shape can only contain one text. If you want to add more than one text then you need to convert the shape into a grouped shape. Then you can add a shape to the group and set that sub-shape's text to what you want.
Shape .Characters object used in conjunction with .Text allows for some flexibility.
private string nl = Environment.NewLine;
public void MultiText() {
try {
// using = System.Windows.Forms;
// using Vis = Microsoft.Office.Interop.Visio;
Vis.Application app = Globals.ThisAddIn.Application; // or launch Visio
Vis.Document vDoc = app.Documents.Add(""); // new blank document
Vis.Shape c1 = app.ActivePage.DrawOval(1, 1, 1.5, 1.5);
Vis.Shape s1 = app.ActivePage.DrawLine(1.5, 1.25, 4, 1.25);
s1.Text = $"Shape1{nl}Line2";
Vis.Shape c2 = app.ActivePage.DrawOval(4, 1, 4.5, 1.5);
Vis.Shape c3 = app.ActivePage.DrawOval(1, 3, 1.5, 3.5);
Vis.Shape s2 = app.ActivePage.DrawLine(1.5, 3.25, 4, 3.25);
s2.Text = $"Shape2";
Vis.Shape c4 = app.ActivePage.DrawOval(4, 3, 4.5, 3.5);
app.ActiveWindow.CenterViewOnShape(c4, Vis.VisCenterViewFlags.visCenterViewDefault);
app.ActiveWindow.Zoom = 1.2;
app.ActiveWindow.Selection.DeselectAll();
app.DoCmd((short)VisUICmds.visCmdDeselectAll);
System.Windows.Forms.MessageBox.Show($"2 Shapes with text.", "Continue...");
// reset the Text on Shape #2 and define 2 separate ranges
s2.Text = "";
// alocate a range
Characters range1 = s2.Characters;
range1.Begin = 0;
range1.End = 3;
range1.Text = "Name";
// alocate another
Characters range2 = s2.Characters;
range2.Begin = 4;
//range2.End = 7;
range2.Text = $"{Environment.NewLine}Type";
MessageBox.Show($"Now change Font Size", "Continue...");
// change font size or any of numerous properties
range1.CharProps[(short)Vis.VisCellIndices.visCharacterSize] = 16;
range2.CharProps[(short)Vis.VisCellIndices.visCharacterSize] = 8;
//range2.CharProps[(short)Vis.VisCellIndices.visCharacterStrikethru] = 1; // 1-true 0-false
MessageBox.Show($"Big Name!{nl}little Type.", "OK to continue");
} catch (Exception ex) {
ta.LogIt($"Err {ex.Message} Trace {ex.StackTrace}");
}
}
You may want to check this post and used the uploaded stencil. (Requires registration to see and download the attachment):
http://visguy.com/vgforum/index.php?topic=6318.msg25957#msg25957

Aspose pdf table

i have added a table with two rows and two columns and set border to all cells. but it shows the border only for first column
Sample code is shown below
var tableestdet = new Table
{
ColumnWidths = "120,120",
Margin = new MarginInfo { Top = 40, Left = 10 },
DefaultCellBorder = new BorderInfo((int)BorderSide.All, 1F),
};
tableestdet.DefaultCellTextInfo = new TextInfo { Alignment = AlignmentType.Center };
var estdet1 = tableestdet.Rows.Add();
estdet1.DefaultRowCellPadding = new MarginInfo { Top = 5, Bottom = 5 };
var req=estdet1.Cells.Add("Requested By:");
var estde=estdet1.Cells.Add("Entered By:");
var estdet2 = tableestdet.Rows.Add();
estdet2.DefaultCellTextInfo = new TextInfo
{
FontSize = 8,
Alignment = AlignmentType.Center
};
estdet2.DefaultRowCellPadding = new MarginInfo { Top = 5, Bottom = 5 };
estdet2.Cells.Add(Requestedby);
estdet2.Cells.Add(CustomerName);
sec1.Paragraphs.Add(tableestdet);
We have noticed that you are working with an outdated version of the API so please upgrade to Aspose.PDF for .NET 19.2 which is latest available version of the API as it includes more features and bug fixes. You may use below code snippet to add a table on page of PDF document, while setting borders for all cells.
// Load source PDF document
Aspose.Pdf.Document document = new Aspose.Pdf.Document();
// Add a page to the document
Page page = document.Pages.Add();
// Initializes a new instance of the Table
Aspose.Pdf.Table table = new Aspose.Pdf.Table();
// Set the table border color as LightGray
table.Border = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, .5f, Aspose.Pdf.Color.FromRgb(System.Drawing.Color.LightGray));
// Set the border for table cells
table.DefaultCellBorder = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, .5f, Aspose.Pdf.Color.FromRgb(System.Drawing.Color.LightGray));
// Create a loop to add 10 rows
for (int row_count = 1; row_count <= 10; row_count++)
{
// Add row to table
Aspose.Pdf.Row row = table.Rows.Add();
// Add table cells
row.Cells.Add("Column (" + row_count + ", 1)");
row.Cells.Add("Column (" + row_count + ", 2)");
}
// Add table object to first page of input document
page.Paragraphs.Add(table);
// Save updated document containing table object
document.Save(dataDir + "Table_19.2.pdf");
Generated PDF document has been attached for your kind reference Table19.2.pdf. Please feel free to let us know if you need any further assistance.
PS: I work with Aspose as Developer Evangelist.

Select and merge a range of cells

I am trying to select the range A1 to C3 to affect a value but this code is not working:
worksheet.Select["A1:C3"].Value = "toto";
I am able to affect the value to each of the cell with this code (but that's not what I want):
worksheet.Cells["A1:C3"].Value = "toto";
I want to merge all cells from A1 to C3, and that this new cell contains toto value;
You first have to merge the cells like this:
worksheet.Cells["A1:C3"].Merge = true;
then to set the value you would either do this:
worksheet.Cells["A1:C3"].Value = "toto";
or set A1 to the value (since it's merged)
worksheet.Cells["A1"].Value = "toto";
Kelsey's method is more diect but if you want to use the Select methods for some reason:
[TestMethod]
public void MergeCellTest()
{
var existingFile = new FileInfo(#"c:\temp\temp.xlsx");
if (existingFile.Exists)
existingFile.Delete();
using (var package = new ExcelPackage(existingFile))
{
var workbook = package.Workbook;
var worksheet = workbook.Worksheets.Add("newsheet");
worksheet.Select("A1:C3");
worksheet.SelectedRange.Merge = true;
worksheet.SelectedRange.Value = "toto";
package.Save();
}
}

Bullet points in Word with c# Interop

I have the following code which is supposed to add a bulleted list to a word document that I'm generating automatically. From other answers I believe the code is correct, but the result doesn't produce any bullet points at all, it doesn't seem to apply the indent either.
Any Ideas?
Microsoft.Office.Interop.Word.Paragraph assets;
assets = doc.Content.Paragraphs.Add(Type.Missing);
// Some code to generate the text
foreach (String asset in assetsList)
{
assetText = assetText + asset + "\n";
}
assets.Range.ListFormat.ApplyBulletDefault(Type.Missing);
// Add it to the document
assets.Range.ParagraphFormat.LeftIndent = -1;
assets.Range.Text = assetText;
assets.Range.InsertParagraphAfter();
This happens because you're adding multiple paragraphs to the range after the range (it seems that setting the Text property is equivalent to InsertAfter). You want to InsertBefore the range so that the formatting you set gets applied.
Paragraph assets = doc.Content.Paragraphs.Add();
assets.Range.ListFormat.ApplyBulletDefault();
string[] bulletItems = new string[] { "One", "Two", "Three" };
for (int i = 0; i < bulletItems.Length; i++)
{
string bulletItem = bulletItems[i];
if (i < bulletItems.Length - 1)
bulletItem = bulletItem + "\n";
assets.Range.InsertBefore(bulletItem);
}
Notice that we add an End of Paragraph mark to all items except the last one. You will get an empty bullet if you add one to the last.
This is based on Tergiver's answer. The difference is it inserts the list items in the correct order after the initially created paragraph. For your own use make the starting range equal to the item you want to insert the list after.
Paragraph assets = doc.Content.Paragraphs.Add();
rng = assets.Range;
rng.InsertAfter("\n");
start = rng.End;
end = rng.End;
rng = _oDoc.Range(ref start, ref end);
object listType = 0;
rng.ListFormat.ApplyBulletDefault(ref listType);
string[] bulletItems = new string[] { "One", "Two", "Three" };
for (int i = 0; i < bulletItems.Length; i++)
{
string bulletItem = bulletItems[i];
if (i < RowCount - 1)
bulletItem = bulletItem + "\n";
rng.InsertAfter(bulletItem);
}
Please note I don't really understand what I'm doing with the range here. This solution was arrived at after considerable trial and error. I suspect it may have to do with the fact that I'm reusing the same range and Tergiver's solution is grabbing a new range each time the range is accessed. I particularly don't understand the following lines:
rng.InsertAfter("\n");
start = rng.End;
end = rng.End;
rng = _oDoc.Range(ref start, ref end);
Generally any alterations to the above code and the list gets intermingled with the previous element. If somebody could explain why this works, I'd be grateful.
You can try below code block if you want list-sublist relations:
static void Main(string[] args)
{
try
{
Application app = new Application();
Document doc = app.Documents.Add();
Range range = doc.Range(0, 0);
range.ListFormat.ApplyNumberDefault();
range.Text = "Birinci";
range.InsertParagraphAfter();
ListTemplate listTemplate = range.ListFormat.ListTemplate;
//range.InsertAfter("Birinci");
//range.InsertParagraphAfter();
//range.InsertAfter("İkinci");
//range.InsertParagraphAfter();
//range.InsertAfter("Üçüncü");
//range.InsertParagraphAfter();
Range subRange = doc.Range(range.StoryLength - 1);
subRange.ListFormat.ApplyBulletDefault();
subRange.ListFormat.ListIndent();
subRange.Text = "Alt Birinci";
subRange.InsertParagraphAfter();
ListTemplate sublistTemplate = subRange.ListFormat.ListTemplate;
Range subRange2 = doc.Range(subRange.StoryLength - 1);
subRange2.ListFormat.ApplyListTemplate(sublistTemplate);
subRange2.ListFormat.ListIndent();
subRange2.Text = "Alt İkinci";
subRange2.InsertParagraphAfter();
Range range2 = doc.Range(range.StoryLength - 1);
range2.ListFormat.ApplyListTemplateWithLevel(listTemplate,true);
WdContinue isContinue = range2.ListFormat.CanContinuePreviousList(listTemplate);
range2.Text = "İkinci";
range2.InsertParagraphAfter();
Range range3 = doc.Range(range2.StoryLength - 1);
range3.ListFormat.ApplyListTemplate(listTemplate);
range3.Text = "Üçüncü";
range3.InsertParagraphAfter();
string path = Environment.CurrentDirectory;
int totalExistDocx = Directory.GetFiles(path, "test*.docx").Count();
path = Path.Combine(path, string.Format("test{0}.docx", totalExistDocx + 1));
app.ActiveDocument.SaveAs2(path, WdSaveFormat.wdFormatXMLDocument);
doc.Close();
Process.Start(path);
}
catch (Exception exception)
{
throw;
}
}
Attention this point: If you don't know input length, you must not define the end of range value like this:
static void Main(string[] args)
{
try
{
Application app = new Application();
Document doc = app.Documents.Add();
Range range = doc.Range(0, 0);
range.ListFormat.ApplyNumberDefault();
range.Text = "Birinci";
range.InsertParagraphAfter();
ListTemplate listTemplate = range.ListFormat.ListTemplate;
//range.InsertAfter("Birinci");
//range.InsertParagraphAfter();
//range.InsertAfter("İkinci");
//range.InsertParagraphAfter();
//range.InsertAfter("Üçüncü");
//range.InsertParagraphAfter();
Range subRange = doc.Range(range.StoryLength - 1, range.StoryLength - 1);
subRange.ListFormat.ApplyBulletDefault();
subRange.ListFormat.ListIndent();
subRange.Text = "Alt Birinci";
subRange.InsertParagraphAfter();
ListTemplate sublistTemplate = subRange.ListFormat.ListTemplate;
Range subRange2 = doc.Range(subRange.StoryLength - 1, range.StoryLength - 1);
subRange2.ListFormat.ApplyListTemplate(sublistTemplate);
subRange2.ListFormat.ListIndent();
subRange2.Text = "Alt İkinci";
subRange2.InsertParagraphAfter();
Range range2 = doc.Range(range.StoryLength - 1, range.StoryLength - 1);
range2.ListFormat.ApplyListTemplateWithLevel(listTemplate,true);
WdContinue isContinue = range2.ListFormat.CanContinuePreviousList(listTemplate);
range2.Text = "İkinci";
range2.InsertParagraphAfter();
Range range3 = doc.Range(range2.StoryLength - 1, range.StoryLength - 1);
range3.ListFormat.ApplyListTemplate(listTemplate);
range3.Text = "Üçüncü";
range3.InsertParagraphAfter();
string path = Environment.CurrentDirectory;
int totalExistDocx = Directory.GetFiles(path, "test*.docx").Count();
path = Path.Combine(path, string.Format("test{0}.docx", totalExistDocx + 1));
app.ActiveDocument.SaveAs2(path, WdSaveFormat.wdFormatXMLDocument);
doc.Close();
Process.Start(path);
}
catch (Exception exception)
{
throw;
}
}
You just need to keep track of the start and end positions of the list and then apply the list format.
Application wordApp = new Application() {
Visible = true
};
Document doc = wordApp.Documents.Add();
Range range = doc.Content;
range.Text = "Hello world!";
range.InsertParagraphAfter();
range = doc.Paragraphs.Last.Range;
// start of list
int startOfList = range.Start;
// each \n character adds a new paragraph...
range.Text = "Item 1\nItem 2\nItem 3";
// ...or insert a new paragraph...
range.InsertParagraphAfter();
range = doc.Paragraphs.Last.Range;
range.Text = "Item 4\nItem 5";
// end of list
int endOfList = range.End;
// insert the next paragraph before applying the format, otherwise
// the format will be copied to the suceeding paragraphs.
range.InsertParagraphAfter();
// apply list format
Range listRange = doc.Range(startOfList, endOfList);
listRange.ListFormat.ApplyBulletDefault();
range = doc.Paragraphs.Last.Range;
range.Text = "Bye for now!";
range.InsertParagraphAfter();

Categories