C#- Pull column from Excel to a Checkbox list - c#

I'm trying to pull the info in a column in excel and show it on a Checkbox List in Windows forms.
Right now I have a list of application names in an excel sheet, I am trying to put the cell values into a string array and attach it to the checklist box.
This is my forms class which handles the windows form:
public Form1()
{
InitializeComponent();
//FilesList filesList = new FilesList();
//AppList testApp = new AppList();
//filesList.DirSearch(#"C:\Users\dbell\Downloads\");
Excel e = new Excel(#"SupportedApps.xlsx", 1);
String[] list = e.ReadApplication();
try
{
checkedListBox1.Items.AddRange(list);
}
catch (ArgumentNullException F)
{
Console.WriteLine("Error: " + F.ToString());
}
}
And this below is my poor attempt to create a method which returns a string array from my worksheet:
public string[] ReadApplication()
{
int column = 0;
int row = 1;
int stringNum = 0;
string[] result = null;
try
{
while (ws.Cells[row, column].Value2 != null)
{
result[stringNum] = ws.Cells[row, column].Value2;
row++;
stringNum++;
}
}
catch(NullReferenceException e)
{
Console.WriteLine("Error: " + e.ToString());
}
return result;
}
At the moment I keep getting null results. I have been able to get this working as a CSV file, however I would like to work with only one excel sheet.
Thanks in advance

Try to use https://www.nuget.org/packages/ClosedXML/ library.
ClosedXML.Excel.IXLWorkbook workbook = new XLWorkbook(#"D:\Test.xlsx");
var worksheet = workbook.Worksheets.First();
int column = 1;
int row = 1;
int stringNum = 0;
List<string> result = new List<string>();
try
{
while (worksheet.Cell(row, column).Value != null && row < worksheet.RowCount())
{
result.Add(worksheet.Cell(row, column).Value.ToString());
row++;
stringNum++;
}
}
catch (NullReferenceException e)
{
Console.WriteLine("Error: " + e.ToString());
}

Related

Excel file (.xlsx) created by using DocumentFormat.OpenXML needs to be repaired when opening in Excel

I have a method which create an excel file (.xlsx) from a list of strings using DocumentFormat.OpenXml. The created file needs to be repaired when I try to open it with Excel 2016. When I click "Yes" Excel shows my file correctly.
Does anyone have any suggestions? Thanks in advance.
Here's my code:
private byte[] ExportDataXlsx(System.Data.Common.DbDataReader reader, string[] fields, string[] headers, string Culture) {
System.IO.MemoryStream sw = new System.IO.MemoryStream();
using (var workbook = Packaging.SpreadsheetDocument.Create(sw, SpreadsheetDocumentType.Workbook)) {
var sheetData = CreateSheet(workbook);
while (reader.Read()) {
Spreadsheet.Row newRow = new Spreadsheet.Row();
foreach (string column in fields) {
Spreadsheet.Cell cell = new Spreadsheet.Cell();
cell.DataType = Spreadsheet.CellValues.String;
object value = null;
try {
int index = reader.GetOrdinal(column);
cell.DataType = DbKymosDomainService.ToXlsType(reader.GetFieldType(index));
value = DbKymosDomainService.ToStringFromCulture(reader.GetValue(index), reader.GetFieldType(index), Culture);
if (cell.DataType == Spreadsheet.CellValues.Number){
value = value == null ? "" : value.ToString().Replace(",", ".");
}
}
catch { }
cell.CellValue = new Spreadsheet.CellValue(value == null ? null : value.ToString()); //
newRow.AppendChild(cell);
try { var x = newRow.InnerXml; } catch { newRow.RemoveChild(cell); }
}
sheetData.AppendChild(newRow);
}
workbook.Close();
}
byte[] data = sw.ToArray();
sw.Close();
sw.Dispose();
return data;
}
Function which create sheet:
private Spreadsheet.SheetData CreateSheet(Packaging.SpreadsheetDocument workbook)
{
var workbookPart = workbook.AddWorkbookPart();
workbook.WorkbookPart.Workbook = new Spreadsheet.Workbook();
workbook.WorkbookPart.Workbook.Sheets = new Spreadsheet.Sheets();
var sheetPart = workbook.WorkbookPart.AddNewPart<Packaging.WorksheetPart>();
var sheetData = new Spreadsheet.SheetData();
sheetPart.Worksheet = new Spreadsheet.Worksheet(sheetData);
Spreadsheet.Sheets sheets = workbook.WorkbookPart.Workbook.GetFirstChild<Spreadsheet.Sheets>();
string relationshipId = workbook.WorkbookPart.GetIdOfPart(sheetPart);
uint sheetId = 1;
if (sheets.Elements<Spreadsheet.Sheet>().Count() > 0) {
sheetId =
sheets.Elements<Spreadsheet.Sheet>().Select(s => s.SheetId.Value).Max() + 1;
}
Spreadsheet.Sheet sheet = new Spreadsheet.Sheet() { Id = relationshipId, SheetId = sheetId, Name = "Export" };
sheets.Append(sheet);
return sheetData;
}
In my experience when a file needs to be repaired after creating it using OpenXML it means that it is missing a crucial element or the crucial element is in the wrong place. I'm having difficulty following your code so that in itself points to something being in the wrong place. Code should be sequential and self-explanatory. A few pointers however to help with getting to the root cause of your issue.
I would suggest first using ClosedXML as it takes so much strain out of the coding.https://github.com/closedxml/closedxml
Debug your code and step through each step to see what's going on.
Open the created file in OpenXML Productivity Tool https://github.com/OfficeDev/Open-XML-SDK/releases/tag/v2.5 and have a look around.
Another tool that I couldn't be without is OpenXML FileViewer: https://github.com/davecra/OpenXmlFileViewer
Lastly I always run this sub routine to validate documents I create using OpenXML:
public static List<string> ValidateWordDocument(FileInfo filepath, ref Int32 maxerrors = 100)
{
try
{
using (WordprocessingDocument wDoc = WordprocessingDocument.Open(filepath.FullName, false))
{
OpenXmlValidator validator = new OpenXmlValidator();
int count = 0;
List<string> er = new List<string>()
{
string.Format($"Assessment of {filepath.Name} on {DateTime.Now} yielded the following result: {Constants.vbCrLf}")
};
// set at zero so that we can determine the total quantity of errors
validator.MaxNumberOfErrors = 0;
// String.Format("<strong> Warning : </strong>")
foreach (ValidationErrorInfo error in validator.Validate(wDoc))
{
count += 1;
if (count > maxerrors)
break;
er.Add($"Error {count}{Constants.vbCrLf}" + $"Description {error.Description}{Constants.vbCrLf}" + $"ErrorType: {error.ErrorType}{Constants.vbCrLf}" + $"Node {error.Node}{Constants.vbCrLf}" + $"Name {error.Node.LocalName}{Constants.vbCrLf}" + $"Path {error.Path.XPath}{Constants.vbCrLf}" + $"Part: {error.Part.Uri}{Constants.vbCrLf}" + $"-------------------------------------------{Constants.vbCrLf}" + $"Outer XML: {error.Node.OuterXml}" + $"-------------------------------------------{Constants.vbCrLf}");
}
int validatorcount = validator.Validate(wDoc).Count;
switch (validatorcount)
{
case object _ when validatorcount > maxerrors:
{
er.Add($"Returned {count - 1} as this is the Maximum Number set by the system. The actual number of errors in {filepath.Name} is {validatorcount}");
er.Add("A summary list of all error types encountered is given below");
List<string> expectedErrors = validator.Validate(wDoc).Select(_e => _e.Description).Distinct().ToList();
er.AddRange(expectedErrors);
break;
}
case object _ when 1 <= validatorcount && validatorcount <= maxerrors:
{
er.Add($"Returned all {validator} errors in {filepath.Name}");
break;
}
case object _ when validatorcount == 0:
{
er.Add($"No Errors found in document {filepath.Name}");
break;
}
}
return er;
wDoc.Close();
}
}
catch (Exception ex)
{
Information.Err.MessageElevate();
return null;
}
}
It helps greatly with problem solving any potential issues.

adding uers to groups in sharepoint

I'm trying to add a user to a sharepoint group based on data from a csv file. I hope that the code marked in bold might be the error.
1.User x=web.Ensureuser("domain\logonname") function--> shows the following error when tried to print any of its file like (x.Title, x.email) --> "The fiels is not assigned" error.
2.Execytequery()--> "The given key is not fount in the dictionary" error.
Please help me with this.
static void Main(string[] args)
{
DataTable dtErrors = new DataTable();
dtErrors.Columns.Add("Links");
dtErrors.Columns.Add("Message");
DataRow drOutputError = dtErrors.NewRow();
DataTable dtCsv = csvToDataTable(System.Configuration.ConfigurationSettings.AppSettings["FilePath"].ToString(), true);
string url = string.Empty;
try
{
foreach (DataRow drCSV in dtCsv.Rows)
{
try
{
url = drCSV[0].ToString();
string grpName = drCSV[1].ToString();
string users = drCSV[2].ToString();
string[] users1 = users.Split(';');
Console.WriteLine("URL picked from CSV: " + url);
using (ClientContext context = new ClientContext(url))
{
Web web = context.Web;
GroupCollection groupColl = web.SiteGroups;
context.Load(groupColl, groups => groups.Include(group => group.Title, group => group.Id));
context.ExecuteQuery();
Console.WriteLine("Groups Count: " + groupColl.Count);
foreach (Group grp in groupColl)
{
try
{
int grpId = grp.Id;
Console.WriteLine("SiteURL: " + url);
Console.WriteLine("Group Name: " + grpName);
//For test purpose
Console.WriteLine(grp.Title);
if (grpName == grp.Title)
{
Console.WriteLine("Match found");
for (int i = 1; i < users1.Length; i++)
{
string temp = users1[i].Remove(0,8);
Console.WriteLine(temp);
**User user = web.EnsureUser(temp);**
Console.WriteLine(user);
addUsersToGroup(grpId, url, user);
}
break;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
drOutputError["Links"] = url;
drOutputError["Message"] = ex.Message.ToString();
dtErrors.Rows.Add(drOutputError);
drOutputError = dtErrors.NewRow();
}
}
}
}
catch (Exception ex)
{
drOutputError["Links"] = url;
drOutputError["Message"] = ex.Message.ToString();
dtErrors.Rows.Add(drOutputError);
drOutputError = dtErrors.NewRow();
}
}
}
catch (Exception ex)
{
drOutputError["Links"] = url;
drOutputError["Message"] = ex.Message.ToString();
dtErrors.Rows.Add(drOutputError);
drOutputError = dtErrors.NewRow();
}
ToCSVError(dtErrors, ",", true);
Console.WriteLine("=======================Completed==================");
Console.ReadLine();
}
public static void addUsersToGroup(int grpId, string url,User user)
{
try
{
using (ClientContext clientContext = new ClientContext(url))
{
Web web = clientContext.Web;
Group testingOwnersGroup = web.SiteGroups.GetById(grpId);
clientContext.Load(testingOwnersGroup);
clientContext.ExecuteQuery();
Console.WriteLine(testingOwnersGroup.Title);
UserCollection collUser = testingOwnersGroup.Users;
collUser.AddUser(user);
clientContext.Load(collUser);
clientContext.Load(testingOwnersGroup);
**clientContext.ExecuteQuery();**
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
}
public static DataTable csvToDataTable(string file, bool isRowOneHeader)
{
DataTable csvDataTable = new DataTable();
//no try/catch - add these in yourselfs or let exception happen
String[] csvData = System.IO.File.ReadAllLines(file);
//if no data in file ‘manually’ throw an exception
if (csvData.Length == 0)
{
// throw new Exception(CSV File Appears to be Empty”);
}
String[] headings = csvData[0].Split(',');
int index = 0; //will be zero or one depending on isRowOneHeader
if (isRowOneHeader) //if first record lists headers
{
index = 1; //so we won’t take headings as data
//for each heading
for (int i = 0; i < headings.Length; i++)
{
//replace spaces with underscores for column names
headings[i] = headings[i].Replace(" ", "_");
//add a column for each heading
csvDataTable.Columns.Add(headings[i], typeof(string));
}
}
else //if no headers just go for col1, col2 etc.
{
for (int i = 0; i < headings.Length; i++)
{
//create arbitary column names
csvDataTable.Columns.Add("col" + (i + 1).ToString(), typeof(string));
}
}
//populate the DataTable
for (int i = index; i < csvData.Length; i++)
{
//create new rows
DataRow row = csvDataTable.NewRow();
for (int j = 0; j < headings.Length; j++)
{
//fill them
row[j] = csvData[i].Split(',')[j];
}
//add rows to over DataTable
csvDataTable.Rows.Add(row);
}
//return the CSV DataTable
return csvDataTable;
}
static void ToCSVError(DataTable table, string delimiter, bool includeHeader)
{
StringBuilder result = new StringBuilder();
if (includeHeader)
{
foreach (DataColumn column in table.Columns)
{
result.Append(column.ColumnName);
result.Append(delimiter);
}
result.Remove(--result.Length, 0);
result.Append(Environment.NewLine);
}
foreach (DataRow row in table.Rows)
{
foreach (object item in row.ItemArray)
{
if (item is System.DBNull)
result.Append(delimiter);
else
{
string itemAsString = item.ToString();
// Double up all embedded double quotes
itemAsString = itemAsString.Replace("\"", "\"\"");
// To keep things simple, always delimit with double-quotes
// so we don't have to determine in which cases they're necessary
// and which cases they're not.
itemAsString = "\"" + itemAsString + "\"";
result.Append(itemAsString + delimiter);
}
}
result.Remove(--result.Length, 0);
result.Append(Environment.NewLine);
}
using (StreamWriter writer = new StreamWriter(System.Configuration.ConfigurationSettings.AppSettings["ErrorLog"].ToString(), true))
{
writer.Write(result.ToString());
}
}
}
}

Exception occurs when trying to pass value to crystal report text box object

I am trying to pass value from C# code to a CrystalReport report.
Edit
private void PrintOrder(List<OrderPrintBO> pListOrderBO)
{
DSOrderReport oDSOrderReport = new DSOrderReport();
DataTable oDataTable = oDSOrderReport.Tables[0];
String sOrderNo = "";
if (pListOrderBO.Count > 0)
{
for (int i = 0; i < pListOrderBO.Count; i++)
{
DataRow oRow = oDataTable.NewRow();
oRow["OrderID"] = pListOrderBO[i].OrderID;
oRow["OrderNumber"] = pListOrderBO[i].OrderNumber;
sOrderNo = pListOrderBO[i].OrderNumber;
oDataTable.Rows.Add(oRow);
}
}
oDSOrderReport.Merge(oDataTable);
oDSOrderReport.AcceptChanges();
if (oDSOrderReport.Tables[0].Rows.Count > 0)
{
// Main Copy
PrintDialog printDialog = new PrintDialog();
rptOrder oMainOrder = new rptOrder();
String sCompanyName = System.Configuration.ConfigurationManager.AppSettings["CompanyName"].ToString();
String sPhone1 = System.Configuration.ConfigurationManager.AppSettings["Phone1"].ToString();
String sPhone2 = System.Configuration.ConfigurationManager.AppSettings["Phone2"].ToString();
String sShowOrderNo = System.Configuration.ConfigurationManager.AppSettings["ShowOrderNo"].ToString();
((CrystalDecisions.CrystalReports.Engine.TextObject)oMainOrder.ReportDefinition.ReportObjects["txtCompanyName"]).Text = sCompanyName;
((CrystalDecisions.CrystalReports.Engine.TextObject)oMainOrder.ReportDefinition.ReportObjects["txtPhone1"]).Text = "Tel:" + sPhone1;
((CrystalDecisions.CrystalReports.Engine.TextObject)oMainOrder.ReportDefinition.ReportObjects["txtPhone2"]).Text = "Tel:" + sPhone2;
////This commented out section gives exception
//string sVarOrderNo = "";
//if (sShowOrderNo.ToLower() == "yes")
//{
// sVarOrderNo = sOrderNo;
//}
//((CrystalDecisions.CrystalReports.Engine.TextObject)oMainOrder.ReportDefinition.ReportObjects["txtOrderNo"]).Text = "O.N. : " + sVarOrderNo;
oMainOrder.SetDataSource(oDSOrderReport);
oMainOrder.PrintOptions.PrinterName = printDialog.PrinterSettings.PrinterName;
try
{
oMainOrder.PrintToPrinter(1, false, 0, 0);
MessageBox.Show("Order Printed Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
else
{
MessageBox.Show("Error in Printing Order", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
End Edit
For the first three text boxes (CompanyName, Phone1 & Phone2), every thing working just fine, but when I tried to pass the OrderNo to the report, Index was outside the bounds of the array. exception is occured, even though my report have a TextBox object named txtOrderNo
I am not sure why this is happening. Please help. Thanks.
Try to change your sOrderNo related code is as below.
string sVarOrderNo = "";
if (sShowOrderNo.ToLower() == "yes")
{
sVarOrderNo = sOrderNo;
}
((CrystalDecisions.CrystalReports.Engine.TextObject)oMainOrder.ReportDefinition.ReportObjects["txtOrderNo"]).Text = "O.N. : " + sVarOrderNo;
UPDATE
Your problem is below mentioned code snippet.Inside the for loop you try to assign a value to sOrderNo. Which is meaningless.B'cos it overrides every time when loop goes.So what is the purpose of this ? If you need this value then you have to bring this value through as your table's row or as a parameter to the report.
if (pListOrderBO.Count > 0)
{
for (int i = 0; i < pListOrderBO.Count; i++)
{
DataRow oRow = oDataTable.NewRow();
oRow["OrderID"] = pListOrderBO[i].OrderID;
oRow["OrderNumber"] = pListOrderBO[i].OrderNumber;
sOrderNo = pListOrderBO[i].OrderNumber;
oDataTable.Rows.Add(oRow);
}
}
I hope this will help to you.

MouseHover Event on DataGridView - Index Out of Range

I have a winforms application with a DataGridView, and have been trying to set up a MouseHover event which provides some more detailed information about the cell being hovered over.
My code is as follows:
private void dataCaseHistory_MouseHover(object sender, EventArgs e)
{
try
{
DataGridView grid = (DataGridView)sender;
Point clientPos = grid.PointToClient(Control.MousePosition);
DataGridViewCell cell = (DataGridViewCell)grid[clientPos.X, clientPos.Y];
int cellRow = cell.RowIndex;
int cellColumn = cell.ColumnIndex;
DataTable table = (DataTable)dataCaseHistory.DataSource;
int docColumn = table.Columns.IndexOf("Doc");
if (cellColumn == docColumn)
{
var varBundleID = table.Rows[cellRow]["BundleID"];
if (varBundleID != DBNull.Value && varBundleID != null)
{
int bundleID = (int)varBundleID;
cBundle bundle = new cBundle(bundleID);
string header = "Bundle: '" + bundle.Name + "'";
string body = "";
foreach (DataRow row in bundle.DocumentBundle.Rows)
{
int docID = (int)row["DocumentID"];
cDocument doc = new cDocument(docID);
body += doc.DocumentName + Environment.NewLine;
}
MessageBox.Show(body, header);
}
else
{
var varDocID = table.Rows[cellRow]["DocID"];
if (varDocID != DBNull.Value && varDocID != null)
{
int docID = (int)varDocID;
cDocument doc = new cDocument(docID);
string header = "Document";
string body = doc.DocumentName;
MessageBox.Show(body, header);
}
}
}
}
catch (Exception eX)
{
string eM = "Error occurred when Single Clicking a Document link in the History tab";
aError err = new aError(eX, eM);
MessageBox.Show(eX.Message, eM);
}
}
But I get an index out of range error as soon as the form loads and whenever I move my mouse. I've never used this event before, so I'd be most appreciative if someone could point out where I am going wrong.
The Item[] property which you access in this line of code:
DataGridViewCell cell = (DataGridViewCell)grid[clientPos.X, clientPos.Y];
is indexed by row and column not by screen coordinates, so your screen coordinates are probably much higher than the number of rows or columns in your grid, therefore causing IndexOutOfRange exception.
You should get the cell using the HitTestInfo class:
MouseEventArgs args = (MouseEventaArgs) e;
DataGridView.HitTestInfo hitTest = this.grid.HitTest(args.X, args.Y);
if (hitTest.Type == DataGridViewHitTestType.Cell)
{
DataGridViewCell cell = (DataGridViewCell)this.Grid[hitText.ColumnIndex, hitTest.RowIndex];
// execute business logic here
}

Excel file generated from WinForm app via template is sometimes "InVisible"

We have a WinForm application that uses VSTO to generate an Excel file from a Template.
Occasionally (frequently) the file opens (because you can use the cursor keys and the formula and cell changes) but it is invisible. Even if you save the file and open it back up, it is still invisible.
The users use Excel 2007 and pretty much all (6 - 8) of our users experience this problem.
The (temporary) fix I have given them is to choose "Arrange All". When this is done, the worksheet pops into view.
I have seen several causes and fixes for this on the web. Everything from using a graphic in the template that was in Excel 2003, but isn't in Excel 2007.
The template is pretty "simple". It has formulas, fonts and colors and that is about it.
The template (and WinForm application) is deployed to the users via Click Once.
Here is the code from the "ThisWorkbook.cs" file:
public string TemplateTableName;
public string TemplateSelectStatement;
private void ThisWorkbook_Startup(object sender, System.EventArgs e)
{
Properties.Settings.Default.myConnectionString = Registry.GetValue("myConnectionString", Properties.Settings.Default.appConnectionString).ToString();
TemplateTableName = Registry.GetValue("TemplateTableName", string.Empty).ToString();
TemplateSelectStatement = Registry.GetValue("TemplateSelectStatement", string.Empty).ToString();
AppLog.ConnectionString = Properties.Settings.Default.myConnectionString;
}
Here is the code from the "Sheet1.cs" file:
private const int StartingDataRow = 4;
private int LastRow;
private int NextAvailableColumn = 18;
DataSet myDS = new DataSet();
Dictionary<string, object[,]> xlsColumnData = new Dictionary<string, object[,]>();
private void Sheet1_Startup(object sender, System.EventArgs e)
{
try
{
if (Globals.ThisWorkbook.TemplateTableName == string.Empty) throw new Exception("TemplateTableName is not set in the registry.");
if (Globals.ThisWorkbook.TemplateSelectStatement == string.Empty) throw new Exception("TemplateSelectStatement is not set in the registry.");
Application.ScreenUpdating = false;
if (Globals.ThisWorkbook.TemplateTableName.Length > 31)
this.Name = Globals.ThisWorkbook.TemplateTableName.Substring(0, 31);
else
this.Name = Globals.ThisWorkbook.TemplateTableName;
LoadTableData();
LoadDataArrays();
BindDataToColumns();
ApplyFormulas();
ApplyFormatting();
this.Range["B4", missing].Select();
Application.ScreenUpdating = true;
AppLog.WriteEvent(DateTime.Now, Environment.UserName, Environment.MachineName, Globals.ThisWorkbook.TemplateTableName, TraceEventType.Information, "Creating customer list");
Globals.ThisWorkbook.RemoveCustomization();
}
catch (Exception ex)
{
AppLog.Show(ex.Message, "Sheet1_Startup", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, TraceEventType.Error);
}
finally
{
Application.ScreenUpdating = true;
}
}
private void LoadTableData()
{
try
{
Application.Cursor = XlMousePointer.xlWait;
string selectCommandText = Globals.ThisWorkbook.TemplateSelectStatement.Replace("[Bind_Type]", "dbo.GetBindingCodeDescription([Bind_Type]) AS Binding_Description");
SqlDataAdapter da = new SqlDataAdapter(selectCommandText, Public_No_Holdings.Properties.Settings.Default.myConnectionString);
da.SelectCommand.CommandTimeout = 60;
if (da.SelectCommand.Connection.State != ConnectionState.Closed) da.SelectCommand.Connection.Close();
da.Fill(this.myDS);
LastRow = (StartingDataRow + this.myDS.Tables[0].Rows.Count) - 1;
}
catch (Exception ex)
{
AppLog.Show(ex.Message, "Loading Table", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
Application.Cursor = XlMousePointer.xlDefault;
}
}
private void LoadDataArrays()
{
System.Data.DataTable dt = this.myDS.Tables[0];
// insert the data into the object[,]
object[,] rowData;
dt.Columns["Imprint"].ColumnName = "Publisher"; //Alias the Imprint dataset column to populate the "Publisher" xls column
for (int iCol = 0; iCol < dt.Columns.Count; iCol++)
{
rowData = new object[dt.Rows.Count, 1];
for (int iRow = 0; iRow < dt.Rows.Count; iRow++)
{
switch (dt.Columns[iCol].ColumnName)
{
case "EAN":
rowData[iRow, 0] = "'" + dt.Rows[iRow][iCol];
break;
case "IPage_Link":
rowData[iRow, 0] = String.Format("=HYPERLINK(\"{0}\", \"{1}\")", dt.Rows[iRow][iCol], "iPage");
break;
default:
rowData[iRow, 0] = dt.Rows[iRow][iCol];
break;
}
}
xlsColumnData.Add(dt.Columns[iCol].ColumnName, rowData);
}
}
private void BindDataToColumns()
{
NamedRange nr;
Range rng;
foreach (KeyValuePair<string, object[,]> kvp in xlsColumnData)
{
try
{
if (this.Controls.Contains(kvp.Key))
{
nr = (NamedRange)this.Controls[kvp.Key];
// Reduce range (remove header rows)
rng = this.Range[this.Cells[StartingDataRow, nr.Column], this.Cells[LastRow, nr.Column]];
rng.Value2 = kvp.Value;
}
else
{
this.Cells[StartingDataRow - 1, NextAvailableColumn].Value2 = kvp.Key;
rng = this.Range[this.Cells[StartingDataRow, NextAvailableColumn], this.Cells[LastRow, NextAvailableColumn]];
rng.Value2 = kvp.Value;
NextAvailableColumn++;
}
}
catch (Exception ex)
{
AppLog.Show(ex.Message, "BindDataToColumns - " + kvp.Key, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ApplyFormulas()
{
Range rng;
int iCol;
// Book Invoice
iCol = this.BookInvoice.Column;
rng = this.Range[this.Cells[StartingDataRow, iCol], this.Cells[LastRow, iCol]];
rng.Select();
rng.FillDown();
// Your Cost
iCol = this.YourCost.Column;
rng = this.Range[this.Cells[StartingDataRow, iCol], this.Cells[LastRow, iCol]];
rng.Select();
rng.FillDown();
}
private void ApplyFormatting()
{
// For some reason Hyperlink columns get reset
this.IPage_Link.Font.Name = this.EAN.Font.Name;
this.IPage_Link.Font.Size = this.EAN.Font.Size;
((Range)this.Cells[StartingDataRow, 1]).EntireRow.Select();
Application.ActiveWindow.FreezePanes = true;
}

Categories