Exporting to excel when there are special characters in the data ( French descriptions) - export-to-excel

I am exporting data to excel file using Excel query table. There will be a text file with the data containing many rows, each cell is separated by | character. I am dumping the data to excel file using the following code
try
{
//Start Excel and get Application object.
oXL = new Excel.Application();
oXL.Visible = false;
oXL.UserControl = false;
//Get a new workbook.
oWBook = (Excel._Workbook)(oXL.Workbooks.Open(strFilename, 0, false, 5, "", "", true, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false));
oSheet = (Excel._Worksheet)oWBook.ActiveSheet;
oSheet.Activate();
//Create header row 2
oXL.ReferenceStyle = Microsoft.Office.Interop.Excel.XlReferenceStyle.xlR1C1;
Excel.Range oRange2 = oSheet.get_Range("A2", "A2");
oRange2.FormulaR1C1 = HeaderLine1;
//Create header row 2
oRange2 = oSheet.get_Range("A3", "A3");
oRange2.FormulaR1C1 = HeaderLine2;
oRange2 = oSheet.get_Range("A" + StartRowNumber.ToString().Trim(), Missing.Value);
var temp = oSheet.QueryTables.Add("TEXT;" + TextFileName, oRange2, Missing.Value);
temp.Name = TextFileName.ToUpper().Replace(".TXT", "");
temp.PreserveFormatting = true;
temp.AdjustColumnWidth = false;
temp.TextFileStartRow = 1;
temp.TextFileParseType = Microsoft.Office.Interop.Excel.XlTextParsingType.xlDelimited;
temp.TextFileTextQualifier = Microsoft.Office.Interop.Excel.XlTextQualifier.xlTextQualifierDoubleQuote;
temp.TextFileConsecutiveDelimiter = false;
temp.TextFileTabDelimiter = true;
temp.TextFileSemicolonDelimiter = false;
temp.TextFileCommaDelimiter = false;
temp.TextFileSpaceDelimiter = false;
temp.TextFileOtherDelimiter = "|";
temp.TextFilePlatform = 1252;//65001;//1252;//65001;//1200;
//http://en.wikipedia.org/wiki/Code_page
temp.TextFileColumnDataTypes = GetDataType(ColumnDataType);
temp.TextFileTrailingMinusNumbers = true;
temp.Refresh(false);
//temp.Connection.ToString();
temp.Delete();
oXL.ReferenceStyle = Microsoft.Office.Interop.Excel.XlReferenceStyle.xlA1;
oWBook.Save();
oWBook.Close(false, Missing.Value, Missing.Value);
}
catch (Exception ex)
{
oWBook.Close(false, Missing.Value, Missing.Value);
}
finally
{
oXL.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(oSheet);
oSheet = null;
System.Runtime.InteropServices.Marshal.ReleaseComObject(oWBook);
oWBook = null;
System.Runtime.InteropServices.Marshal.ReleaseComObject(oXL);
oXL = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
When the text file contains some special characters( Ex French words) it will not display as they are when the excel file is opened after generating....
Can anyone help to solve this problem ?
Thanks
Suresh

Related

Is it possible to Insert an anchored text frame above a text/word?

I want to mark each CharacterStyle in the document by placing an achored text frame above each text/word. I am quite new to scripting in indesign, so any help is much appreciated.
Here is the expected output:
I found a solution to this, and for those who might encounter the same problem as me here is my code :
app.findChangeGrepOptions.includeFootnotes = false;
app.findChangeGrepOptions.includeHiddenLayers = false;
app.findChangeGrepOptions.includeLockedLayersForFind = false;
app.findChangeGrepOptions.includeLockedStoriesForFind = false;
app.findChangeGrepOptions.includeMasterPages = false;
app.findGrepPreferences = NothingEnum.nothing;
app.findGrepPreferences.appliedCharacterStyle = style;
app.findGrepPreferences.findWhat = ".+";
var found_item = doc.findGrep();
var res_count = found_item.length;
if(res_count > 0){
var found_text = found_item[0].paragraphs.firstItem();
var insertion_character = (found_text.characters.lastItem().index);
var check_insertion_character = insertion_character + 1;
var alt_insertion_character = (found_text.characters.firstItem().index);
var the_story = found_text.parentStory;
try{
app.selection = the_story.insertionPoints[check_insertion_character];
app.selection = the_story.insertionPoints[alt_insertion_character];
}catch(err){
alert(err);
}
var the_anchored_frame = app.selection[0].textFrames.add({geometricBounds:["0","0",1,10],anchoredObjectSettings:{anchoredPosition: AnchorPosition.ABOVE_LINE, horizontalReferencePoint: AnchoredRelativeTo.ANCHOR_LOCATION, verticalReferencePoint: VerticallyRelativeTo.TOP_OF_LEADING}});
the_anchored_frame.contents = style;
// the_anchored_frame.appliedObjectStyle = real_anchor_style;
}
Cheers

format export to excel using closedxml with Title

I am exporting to excel using closedxml my code is working fine, but i want to format my exported excel file with a title, backgroundcolour for the title if possible adding image.
private void button4_Click(object sender, EventArgs e)
{
string svFileName = GetSaveFileName(Convert.ToInt32(comboBox1.SelectedValue));
DataTable dt = new DataTable();
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
dt.Columns.Add(col.HeaderText);
}
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataRow dRow = dt.NewRow();
foreach (DataGridViewCell cell in row.Cells)
{
dRow[cell.ColumnIndex] = cell.Value;
}
dt.Rows.Add(dRow);
}
//if (!Directory.Exists(folderPath))
//{
// Directory.CreateDirectory(folderPath);
//}
if (svFileName == string.Empty)
{
DateTime mydatetime = new DateTime();
SaveFileDialog objSaveFile = new SaveFileDialog();
objSaveFile.FileName = "" + comboBox1.SelectedValue.ToString() + "_" + mydatetime.ToString("ddMMyyhhmmss") + ".xlsx";
objSaveFile.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
objSaveFile.FilterIndex = 2;
objSaveFile.RestoreDirectory = true;
string folderpath = string.Empty;
Cursor.Current = Cursors.WaitCursor;
if (objSaveFile.ShowDialog() == DialogResult.OK)
{
Cursor.Current = Cursors.WaitCursor;
FileInfo fi = new FileInfo(objSaveFile.FileName);
folderpath = fi.DirectoryName;
int rowcount = 0;
int sheetcount = 1;
int temprowcount = 0;
using (XLWorkbook wb = new XLWorkbook())
{
var ws = wb.Worksheets.Add(dt,comboBox1.Text.ToString() + sheetcount.ToString());
ws.Row(1).Height=50;
//ws.FirstRow().Merge();
ws.Row(1).Merge();
//ws.Row(1).Value = comboBox1.Text.ToString();
//ws.Row(1).Cell(1).im
ws.Row(1).Cell(1).Value = comboBox1.Text.ToString();
ws.Row(1).Cell(1).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
ws.Row(1).Cell(1).Style.Alignment.Vertical=XLAlignmentVerticalValues.Center;
ws.Row(1).Cell(1).Style.Fill.BackgroundColor = XLColor.Red;
ws.Row(1).Cell(1).Style.Font.FontColor = XLColor.White;
ws.Row(1).Cell(1).Style.Font.FontSize = 21;
ws.Row(1).Cell(1).Style.Font.Bold = true;
ws.Column(1).Merge();
ws.Column(1).Style.Fill.BackgroundColor = XLColor.Red;
ws.Cell(2, 2).InsertTable(dt);
wb.SaveAs(fi.ToString());
//wb.SaveAs(folderpath + "\\" + comboBox1.SelectedItem.ToString() + "_" + mydatetime.ToString("ddMMyyhhmmss") + ".xlsx");
//rowcount = 0;
//sheetcount++;
//}
}
//}
MessageBox.Show("Report (.xlxs) Saved Successfully.");
}
}
else
{
Cursor.Current = Cursors.WaitCursor;
string folderpath = string.Empty;
folderpath = Properties.Settings.Default.ODRSPath + "\\" + svFileName;
using (XLWorkbook wb = new XLWorkbook())
{
//DateTime mydatetime = new DateTime();
wb.Worksheets.Add(dt, comboBox1.SelectedItem.ToString());
wb.SaveAs(folderpath);
}
MessageBox.Show("Report (.xlxs) Saved Successfully.");
}
}

alias with space in columns using linq and gridview to export excel

I need to export Excel and I'm using MVC4
This is my code
var co = from c in context.AN_COMPANY
orderby c.COMPANY_DESCR
select c;
List<AN_COMPANY_EXT> societa_list = new List<AN_COMPANY_EXT>();
foreach (var o in co)
{
AN_COMPANY_EXT c_ex = new AN_COMPANY_EXT(o);
societa_list.Add(c_ex);
}
GridView gv = new GridView();
gv.DataSource = (from d in societa_list
select new { Codice = d.ID_COMPANY, Descrizione = d.COMPANY_DESCR, SAP_Alias = d.COMPANY_SAP_ALIAS, Booking_Company = d.IS_BOOKING_COMPANY });
gv.DataBind();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=AnagraficaSocieta.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
return RedirectToAction("Index");
How can I set column name with a space, for example "SAP ALIAS" instead of SAP_ALIAS?

How do I convert a Word Table into an embedded Excel Worksheet?

I have a document that has multiple Word Tables. I need to convert them into embedded Excel Worksheets (or COM Objects). I've been able to "import" the Word Tables into Excel using the following:
Excel.Application xlApp = new Excel.Application();
// Call the conversion tool
for (int i = 1; i <= curDoc.Tables.Count; i++ )
{
Word.Table tbl = curDoc.Tables[i];
Word.Range tblLoc = tbl.Range;
// Used for debugging.
xlApp.Visible = true;
if (xlApp == null)
{
messageAlert = "Excel could not be started. Check that your office installation and project references are correct.";
break;
}
Excel.Workbook wb = xlApp.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets[1];
if (ws == null)
{
messageAlert = "Worksheet could not be created. Check that your office installation and project reference are correct.";
break;
}
Word.Range rng = tbl.ConvertToText(Separator: ";", NestedTables: false);
string sData = rng.Text;
string[] rows = sData.Split('\r');
int r = 1, c = 1;
int numRows = rows.Count();
int numCols = rows[0].Split(';').Count();
foreach (string row in rows)
{
string[] cells = row.Split(';');
foreach (string cell in cells)
{
ws.Cells[r, c].Value = cell;
c += 1;
}
r += 1;
c = 1;
}
Problem is whenever I copy the contents back into the document, a new Word Table is created instead of an Excel Worksheet. How do I either import an Excel Worksheet into Word, or directly convert the tables into Excel Worksheets?
In order to do this, you'll have to first save the excel worksheet and then import it as an OLEObject. Here's an example:
public void ConvertTables()
{
string messageAlert = "";
Word.Application curApp = Globals.ThisAddIn.Application;
Word.Document curDoc = curApp.ActiveDocument;
if (curDoc.Tables.Count > 0)
{
Excel.Application xlApp = new Excel.Application();
//Used for debugging.
//xlApp.Visible = true;
//Call the conversion tool
for (int i = 1; i <= curDoc.Tables.Count; i++ )
{
Word.Table tbl = curDoc.Tables[i];
Word.Range tblLoc = tbl.Range;
if (xlApp == null)
{
messageAlert = "Excel could not be started. Check that your office installation and project references are correct.";
break;
}
Excel.Workbook wb = xlApp.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets[1];
if (ws == null)
{
messageAlert = "Worksheet could not be created. Check that your office installation and project reference are correct.";
break;
}
Word.Range rng = tbl.ConvertToText(Separator: ";", NestedTables: false);
string sData = rng.Text;
string[] rows = sData.Split('\r');
int r = 1, c = 1;
int numRows = rows.Count();
int numCols = rows[0].Split(';').Count();
foreach (string row in rows)
{
string[] cells = row.Split(';');
foreach (string cell in cells)
{
ws.Cells[r, c].Value = cell;
c += 1;
}
r += 1;
c = 1;
}
ws.SaveAs("C:\\temp\\test.xlsx");
rng.Text = "";
rng.InlineShapes.AddOLEObject(ClassType: "Excel.Sheet.12", FileName: "C:\\temp\\test.xlsx");
ws.Range["A1", ws.Cells[numRows, numCols]].Value = "";
ws.SaveAs("C:\\Temp\\test.xlsx");
}
xlApp.Quit();
messageAlert = "Tables converted";
}
else
{
// No tables found
messageAlert = "No tables found within the document";
}
MessageBox.Show(messageAlert);
}

Images not showing in excel using npoi

The below code which uses npoi to create excel documents displays images in open office calc but not in excel.
If i open the doc in calc and save the document and then open the document in excel i can then see the images in excel.
Here is the code.
public static byte[] CreateExcel(CampaignViewModel viewModel, string fileName)
{
byte[] output;
using (FileStream fs = new FileStream(HttpContext.Current.Server.MapPath(#"\Data\templates\NPOITemplate.xls"), FileMode.Open, FileAccess.ReadWrite))
{
var templateWorkbook = new HSSFWorkbook(fs, true);
var sheet = templateWorkbook.GetSheet("Sheet1");
var patriarch = sheet.CreateDrawingPatriarch();
var leftFieldHeaders = CsvHelper.GetMatrixAllLeftFields();
var productHeaders = CsvHelper.GetMatrixProducts(viewModel.ProductCampaigns);
var totalCols = leftFieldHeaders.Count + productHeaders.Count;
var colWidth = 5000;
for (int i = 0; i < totalCols; i++)
{
sheet.SetColumnWidth(i, colWidth);
}
var imageRow = sheet.CreateRow(0);
imageRow.Height = 2000;
var imageCellCount = 0;
foreach (var header in leftFieldHeaders)
{
imageRow.CreateCell(imageCellCount).SetCellValue("");
imageCellCount++;
}
foreach (var product in viewModel.ProductCampaigns)
{
try
{
var anchor = new HSSFClientAnchor(0, 0, 0, 0, imageCellCount, 0, imageCellCount, 0);
anchor.AnchorType = 2;
var path = HttpContext.Current.Server.MapPath(product.Product.ImageThumbUrl);
var picture = patriarch.CreatePicture(anchor, LoadImage(#path, templateWorkbook));
picture.Resize();
picture.LineStyle = HSSFPicture.LINESTYLE_SOLID;
}
catch (Exception)
{
}
imageCellCount++;
}
using (MemoryStream ms = new MemoryStream())
{
templateWorkbook.Write(ms);
output = ms.ToArray();
}
}
return output;
}
public static int LoadImage(string path, HSSFWorkbook wb)
{
try
{
var file = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
var buffer = new byte[file.Length];
file.Read(buffer, 0, (int)file.Length);
return wb.AddPicture(buffer, PictureType.JPEG);
}
catch (Exception)
{
return 0;
}
}
i've resolved the above in a round about way. Turns out i didn't really need to use the template and could just create the xls from scratch. This add's a bit more meta data to the file which i suspect was the issue
public static byte[] CreateExcel2(CampaignViewModel viewModel, ICollection<DeliveryPoint> deliveryPoints, string fileName)
{
FileContentResult fileContentResult;
byte[] output;
var matrixCampaignLines = viewModel.MatrixCampaignLines;
HSSFWorkbook hssfworkbook = new HSSFWorkbook();
DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
dsi.Company = "NPOI Team";
hssfworkbook.DocumentSummaryInformation = dsi;
////create a entry of SummaryInformation
SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
si.Subject = "NPOI SDK Example";
hssfworkbook.SummaryInformation = si;
var sheet = hssfworkbook.CreateSheet("Sheet1");
var patriarch = sheet.CreateDrawingPatriarch();
var leftFieldHeaders = (viewModel.Campaign.EnableNameOnCampaign) ? CsvHelper.GetMatrixAllLeftFields() : CsvHelper.GetMatrixAllLeftFieldsWithoutName();
var productHeaders = CsvHelper.GetMatrixProducts(viewModel.ProductCampaigns);
var totalCols = leftFieldHeaders.Count + productHeaders.Count;
var colWidth = 5000;
for (int i = 0; i < totalCols; i++)
{
sheet.SetColumnWidth(i, colWidth);
}
var imageRow = sheet.CreateRow(0);
imageRow.Height = 2000;
var imageCellCount = 0;
foreach (var header in leftFieldHeaders)
{
imageRow.CreateCell(imageCellCount).SetCellValue("");
imageCellCount++;
}
foreach (var product in viewModel.ProductCampaigns)
{
try
{
var anchor = new HSSFClientAnchor(0, 0, 0, 0, imageCellCount, 0, imageCellCount, 0);
anchor.AnchorType = 2;
var path = HttpContext.Current.Server.MapPath(product.Product.ImageThumbUrl);
var picture = patriarch.CreatePicture(anchor, LoadImage(#path, hssfworkbook));
picture.Resize();//Comment this line if your code crashes.
picture.LineStyle = HSSFPicture.LINESTYLE_SOLID; might not
}
catch (Exception)
{
}
imageCellCount++;
}
using (MemoryStream ms = new MemoryStream())
{
hssfworkbook.Write(ms);
output = ms.ToArray();
}
return output;
}
public static int LoadImage(string path, HSSFWorkbook wb)
{
try
{
var file = new FileStream(path, FileMode.Open, FileAccess.Read);
var buffer = new byte[file.Length];
file.Read(buffer, 0, (int)file.Length);
return wb.AddPicture(buffer, PictureType.JPEG);
}
catch (Exception)
{
return 0;
}
}
I got it right now.
I am using
try
{
ISheet sheet = templateWorkbook.GetSheet(sheetName);
HSSFPatriarch patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch();
//create the anchor
HSSFClientAnchor anchor;
anchor = new HSSFClientAnchor(0, 0, 255, 255,
start.Col, start.Row, end.Col, end.Row);
anchor.AnchorType = 2;
patriarch.CreatePicture(anchor,
LoadImage(imagePath, templateWorkbook));
}
catch (IOException ioe)
{
}
and LoadImage() method which returns path from the server.
Use this one. It runs fine.

Resources