Epplus how to remove spaces into my excel & resx file - c#

I'm starting to learn c # and Windows form. I create an application that transforms a resx (XML) file into an Excel.
All my code works, my Excel file is created and I can convert it to a resx file.
But, when I open my Excel file, spaces before and after my data has been added like this : Excel cell example. And when I convert it to resx file, it does
Resx file example
Here is my resx => excel code :
//I use a application WindowsForm so any 'LBL' / 'TXT make reference to label or textBox I use them to set file or folder path
private void writeExcel()
{
Dictionary<string, string> dataSave = new Dictionary<string, string>();
var path = LBL_DocumentPath.Text;
XDocument doc = XDocument.Load(path);
IEnumerable<XNode> nodes = doc.Descendants("data");
foreach (XElement node in nodes)
{
string name = node.Attribute("name").Value;
string value = node.Value;
dataSave.Add(name, value);
}
CreateExcel(dataSave);
}
private void CreateExcel(Dictionary<string, string> dico)
{
int i = 1;
FileInfo newFile = new FileInfo(LBL_FolderPath.Text + "/" + TXT_FileName.Text + ".xlsx");
using (ExcelPackage package = new ExcelPackage(newFile))
{
try
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Inventry");
worksheet.Cells[1, 1].Value = "Name";
worksheet.Cells[1, 2].Value = "value";
worksheet.Cells[1, 3].Value = "translation";
foreach (KeyValuePair<string, string> data in dico)
{
string testMessage = String.Format("{0}", data.Value);
string delSpace = testMessage;
Regex regex = new Regex(#"(\s){2,}");
testMessage = regex.Replace(delSpace, "&");
i++;
worksheet.Cells[i, 1].Value = String.Format("{0}", data.Key);
worksheet.Cells[i, 2].Value = String.Format("{0}", testMessage);
worksheet.Cells.AutoFitColumns();
}
package.Save();
MessageBox.Show("File created ! " + LBL_FolderPath.Text + "\\" + TXT_FileName.Text);
}
catch (Exception)
{
MessageBox.Show("File already exist, checks : " + LBL_DocumentPath.Text + "\\" + TXT_FileName.Text);
}
}
}
If you want all my code, I can give you a dropbox link.
Thanks in advance for any help you can give me.
Math.
Ps: My apologies, my English is not very good. I hope you will understand me correctly

Ok a friend give me solution.
It's my regex which does not work so I replace
string testMessage = String.Format("{0}", data.Value);
string delSpace = testMessage;
Regex regex = new Regex(#"(\s){2,}");
testMessage = regex.Replace(delSpace, "&");
by
string testMessage = String.Format("{0}", data.Value);
testMessage = testMessage.Replace("\n",string.Empty);
testMessage = testMessage.Replace("\r", string.Empty);
testMessage = testMessage.Replace(" ", string.Empty);

Related

how can i get nested data from a JsonConvert.DeserializeObject<dynamic>(example)

Using the example code works correctly to get the non-nested data from "issues", how can I get the nested data from "issues"? In the picture you can see which data we are talking about.
Code:
try
{
var dynObj = JsonConvert.DeserializeObject<dynamic>(strResponseValue);
string records = dynObj["issues"].ToString();
JArray a = JArray.Parse(records);
List<string> colNames = new List<string>() {"expand", "key", "id",
"self" };
string headerRow = "";
foreach (string colName in colNames)
{
headerRow += "\"" + colName + "\";";
}
headerRow = headerRow.TrimEnd(';');
headerRow += "\n";
string dataRows = "";
foreach (var record in a)
{
string thisRecord = "";
foreach (string colName in colNames)
{
thisRecord += "\"" + record[colName] + "\";";
}
thisRecord = thisRecord.TrimEnd(';');
thisRecord += "\n";
dataRows += thisRecord;
}
csvData = headerRow + dataRows;
Console.WriteLine("\ncsvData:");
Console.WriteLine(csvData);
}
catch (Exception ex)
{
Console.WriteLine("Exeption Error" + ex.ToString());
}
If the json is complex, you can let visual studio do the job.
Copy the json content
Use Edit/Paste Special - Paste JSON As Classes
Use the generated Class to deserialize your json content.
For instance deserialize to MyClass (from .Net Fundumentals - JSON Serialize/Deserialize):
MyClass? myclass = JsonSerializer.Deserialize<MyClass>(jsonString);

Mailkit - replace text in Html part

will appreciate any Help on this one.
I am trying to replace text in an email template using Mailkit. The issue is that in Mailkit there is at least a text part and and Html part.
I can get then set the text part using code such as:
var textPart = message.BodyParts.OfType<TextPart>().FirstOrDefault();
I can get the htmlbody using
var htmlPart = message.htmlBody
but once I modify it I do not know how to set the htmlpart to the message's htmlBody.
My code so far:
FileStream sr = new FileStream(fileLocation + "\\" + fileName, FileMode.Open, FileAccess.Read);
message = MimeMessage.Load(sr);
sr.Close();
//Get the text Part
var textPart = message.BodyParts.OfType<TextPart>().FirstOrDefault();
//Get the HtmlBody
var htmlPart = message.HtmlBody;
string regexPattern;
string regexReplacement;
Regex regexText;
foreach (var replaceSet in replaceArray)
{
regexPattern = "#" + replaceSet["Key"].ToString() + "#";
regexReplacement = (string)replaceSet["Value"].ToString();
//bool test = Regex.IsMatch(docText, regexPattern);
if (regexReplacement != "")
{
regexText = new Regex(regexPattern);
textPart.Text = regexText.Replace(textPart.Text, regexReplacement);
//Set, modify the text part
htmlPart = regexText.Replace(htmlPart, regexReplacement);
}
}
try
{
message.WriteTo(fileLocation + "\\output\\" + fileName);
}
catch (Exception Ex)
{
result = Ex.Message;
return BadRequest(result);
}```
Something like this will probably work:
// Get the text Part
var textPart = message.BodyParts.OfType<TextPart>().FirstOrDefault(x => x.IsPlain);
var htmlPart = message.BodyParts.OfType<TextPart>().FirstOrDefault(x => x.IsHtml);
string regexPattern;
string regexReplacement;
Regex regexText;
foreach (var replaceSet in replaceArray)
{
regexPattern = "#" + replaceSet["Key"].ToString() + "#";
regexReplacement = (string)replaceSet["Value"].ToString();
//bool test = Regex.IsMatch(docText, regexPattern);
if (regexReplacement != "")
{
regexText = new Regex(regexPattern);
textPart.Text = regexText.Replace(textPart.Text, regexReplacement);
//Set, modify the text part
htmlPart.Text = regexText.Replace(htmlPart.Text, regexReplacement);
}
}

How to Save word document in a folder which is created by Directory.CreateDirectory(docfile_path)?

This block of code throws an error called file name is invalid.
I want to create a folder named as "test" inside this there will be another folder named as today's date "date" , i want to keep the the word document inside this date folder, please help.
public string File_path;
public string docfile_path;
public string filename;
private void button1_Click(object sender, EventArgs e)
{
string time = DateTime.Now.ToString("HH.mm.ss");
string date = DateTime.Today.ToShortDateString();
docfile_path = File_path+ "test" + date;
Directory.CreateDirectory(docfile_path);
filename = docfile_path + "worddoc"+"-" +".docx";
Word.Application app = new Word.Application();
Word.Document doc = new Word.Document();
try
{
doc = app.Documents.Open(filename);
}
catch
{
}
Word.Paragraph oPara1;
oPara1 = doc.Content.Paragraphs.Add();
oPara1.Range.Text = "Test Result";
oPara1.Range.Font.Bold = 1;
oPara1.Format.SpaceAfter = 24;
oPara1.Range.InsertParagraphAfter();
oPara1.Range.InsertParagraphAfter();
Word.Paragraph oPara2;
oPara2 = doc.Content.Paragraphs.Add();
oPara2.Range.Text = "Test Name";
oPara2.Range.Font.Bold = 1;
oPara2.Format.SpaceAfter = 24;
oPara2.Range.InsertParagraphAfter();
doc.SaveAs2(filename);
doc.Close();
doc = null;
app.Quit();
app = null;
}
Surprisingly enough, this code compile and run, but the outcome is not what you probably wanted.
A couple of things is wrong in this code:
1.you cant add strings like that to create a path, a path should be created with the '/' symbol between directories.
this is a legal path:
string path = #"C:\Users\username\Desktop\Games";
this is not :
string path = #"C:UsersusernameDesktopGames";
you can fix it by using the Path.Combine function as follow:
docfile_path = Path.Combine(File_path , "test" , date);
be sure to this for all path strings (including File_path that is value is not shown in the code above).
2.you should use
Document doc = app.Documents.Add();
to create a new Word document and not
Document doc = new Document();
3.you should use a different format for string date, DateTime.ToShortDateString() is dividing the date with the '/' symbol which will create new folders.
try using:
string date = DateTime.Today.ToString("dd.MM.yyyy");
4.I don't see any reason for the line
doc = app.Documents.Open(filename);
You are trying to open the the file that you intent to create?
here is the code i used:
string File_path = #"C:\Users\yakir\Desktop";
string docfile_path;
string filename;
string time = DateTime.Now.ToString("HH.mm.ss");
string date = DateTime.Today.ToString("dd.MM.yyyy");
docfile_path = Path.Combine(File_path , "test" , date);
Directory.CreateDirectory(docfile_path);
filename = Path.Combine(docfile_path, "worddoc" + "-" + ".docx");
Application app = new Application();
Document doc = app.Documents.Add();
Paragraph oPara1;
oPara1 = doc.Content.Paragraphs.Add();
oPara1.Range.Text = "Test Result";
oPara1.Range.Font.Bold = 1;
oPara1.Format.SpaceAfter = 24;
oPara1.Range.InsertParagraphAfter();
oPara1.Range.InsertParagraphAfter();
Paragraph oPara2;
oPara2 = doc.Content.Paragraphs.Add();
oPara2.Range.Text = "Test Name";
oPara2.Range.Font.Bold = 1;
oPara2.Format.SpaceAfter = 24;
oPara2.Range.InsertParagraphAfter();
doc.SaveAs2(filename);
doc.Close();
doc = null;
app.Quit();
app = null;
}

Read more than one file

I am writing a pdf to word converter which works perfectly fine for me. But I want to be able to convert more than one file.
What happens now is that it read the first file and does the convert process.
public static void PdfToImage()
{
try
{
Application application = null;
application = new Application();
var doc = application.Documents.Add();
string path = #"C:\Users\Test\Desktop\pdfToWord\";
foreach (string file in Directory.EnumerateFiles(path, "*.pdf"))
{
using (var document = PdfiumViewer.PdfDocument.Load(file))
{
int pagecount = document.PageCount;
for (int index = 0; index < pagecount; index++)
{
var image = document.Render(index, 200, 200, true);
image.Save(#"C:\Users\chnikos\Desktop\pdfToWord\output" + index.ToString("000") + ".png", ImageFormat.Png);
application.Selection.InlineShapes.AddPicture(#"C:\Users\chnikos\Desktop\pdfToWord\output" + index.ToString("000") + ".png");
}
string getFileName = file.Substring(file.LastIndexOf("\\"));
string getFileWithoutExtras = Regex.Replace(getFileName, #"\\", "");
string getFileWihtoutExtension = Regex.Replace(getFileWithoutExtras, #".pdf", "");
string fileName = #"C:\Users\Test\Desktop\pdfToWord\" + getFileWihtoutExtension;
doc.PageSetup.PaperSize = WdPaperSize.wdPaperA4;
foreach (Microsoft.Office.Interop.Word.InlineShape inline in doc.InlineShapes)
{
if (inline.Height > inline.Width)
{
inline.ScaleWidth = 250;
inline.ScaleHeight = 250;
}
}
doc.PageSetup.TopMargin = 28.29f;
doc.PageSetup.LeftMargin = 28.29f;
doc.PageSetup.RightMargin = 30.29f;
doc.PageSetup.BottomMargin = 28.29f;
application.ActiveDocument.SaveAs(fileName, WdSaveFormat.wdFormatDocument);
doc.Close();
}
}
I thought that with my foreach that problem should not occur. And yes there are more than one pdf in this folder
The line
var doc = application.Documents.Add();
is outside the foreach loop. So you only create a single word document for all your *.pdf files.
Move the above line inside the foreach loop to add a new word document for each *.pdf file.

find and replace in file xml

i want open file xml and find string then replace.
but when replace string Only to find two strings and replace
this my code
var realpath = "~/template/xml/xmlback";
var filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/template/xml/xmltest") + ".xml");
var filePath2 = Path.Combine(HttpContext.Current.Server.MapPath("~/template/xml/xmlback/test2") + ".xml");
DirectoryInfo dir = new DirectoryInfo(Path.Combine(HttpContext.Current.Server.MapPath(realpath)));
foreach (FileInfo files in dir.GetFiles())
{
files.Delete();
}
string strVal = System.IO.File.ReadAllText(Server.MapPath("~/template/xml/xmltest") + ".xml");
strVal = strVal.Replace("Test1", "amir");
strVal = strVal.Replace("Test2", "amir1");
strVal = strVal.Replace("Test3", "amir2");
strVal = strVal.Replace("Test4", "amir3");
strVal = strVal.Replace("Test5", "amir4");
strVal = strVal.Replace("Test6", "amir5");
File.Copy(Path.Combine(filePath), Path.Combine(filePath2));
System.IO.File.WriteAllText(Server.MapPath("~/template/xml/xmlback/test2") + ".xml", strVal);
ProcessRequest(filePath2, Lcourseid.Text);
im try open xml with word and see resultpic
I've solved my issue
iam use this code But no difference with the above code does not
I think it was a corrupted file xml,
Could not find Test3 and Test4,...
Thank you all
Dictionary<string, string> wordsToReplace = new Dictionary<string, string>();
wordsToReplace.Add("Test1", "amir");
wordsToReplace.Add("Test2", "amir1");
wordsToReplace.Add("Test3", "amir3");
wordsToReplace.Add("Test4", "amir4");
wordsToReplace.Add("Test5", "amir5");
wordsToReplace.Add("Test6", "amir6");
string strVal = System.IO.File.ReadAllText(Server.MapPath("~/template/xml/xmltest") + ".xml");
foreach (var pair in wordsToReplace)
{
//Performs each replacement
strVal = strVal.Replace(pair.Key, pair.Value);
}
File.Copy(Path.Combine(filePath), Path.Combine(filePath2));
System.IO.File.WriteAllText(Server.MapPath("~/template/xml/xmlback/test2") + ".xml", strVal);
ProcessRequest(filePath2, Lcourseid.Text);

Categories