I have been stuck on this issue for a a day or so and need some help. In my application, I have some data in a listview, which is
public void OnHostPing(HostPinger host)
{
if (InvokeRequired)
{
Invoke(new OnPingDelegate(OnHostPing), new object[] { host });
return;
}
lock (_table)
{
ListViewItem item = (ListViewItem)_table[host.ID];
if (item != null)
{
item.SubItems[0].Text = host.HostIP.ToString();
item.SubItems[1].Text = host.HostName;
item.SubItems[2].Text = host.HostDescription;
item.SubItems[3].Text = host.StatusName;
item.SubItems[4].Text = host.SentPackets.ToString();
item.SubItems[5].Text = host.ReceivedPackets.ToString();
item.SubItems[6].Text = PercentToString(host.ReceivedPacketsPercent);
item.SubItems[7].Text = host.LostPackets.ToString();
item.SubItems[8].Text = PercentToString(host.LostPacketsPercent);
item.SubItems[9].Text = host.LastPacketLost ? "Yes" : "No";
item.SubItems[10].Text = host.ConsecutivePacketsLost.ToString();
item.SubItems[11].Text = host.MaxConsecutivePacketsLost.ToString();
item.SubItems[12].Text = host.RecentlyReceivedPackets.ToString();
item.SubItems[13].Text = PercentToString(host.RecentlyReceivedPacketsPercent);
item.SubItems[14].Text = host.RecentlyLostPackets.ToString();
item.SubItems[15].Text = PercentToString(host.RecentlyLostPacketsPercent);
item.SubItems[16].Text = host.CurrentResponseTime.ToString();
item.SubItems[17].Text = host.AverageResponseTime.ToString("F");
item.SubItems[18].Text = host.MinResponseTime.ToString();
item.SubItems[19].Text = host.MaxResponseTime.ToString();
item.SubItems[20].Text = DurationToString(host.CurrentStatusDuration);
item.SubItems[21].Text = DurationToString(host.GetStatusDuration(HostStatus.Alive));
item.SubItems[22].Text = DurationToString(host.GetStatusDuration(HostStatus.Dead));
item.SubItems[23].Text = DurationToString(host.GetStatusDuration(HostStatus.DnsError));
item.SubItems[24].Text = DurationToString(host.GetStatusDuration(HostStatus.Unknown));
item.SubItems[25].Text = PercentToString(host.HostAvailability);
item.SubItems[26].Text = DurationToString(host.TotalTestDuration);
item.SubItems[27].Text = DurationToString(host.CurrentTestDuration);
}
else
{
item = new ListViewItem(new string[]
{
host.HostIP.ToString(), host.HostName, host.HostDescription,
host.StatusName,
host.SentPackets.ToString(),
host.ReceivedPackets.ToString(), PercentToString(host.ReceivedPacketsPercent),
host.LostPackets.ToString(), PercentToString(host.LostPacketsPercent),
host.LastPacketLost ? "Yes" : "No",
host.ConsecutivePacketsLost.ToString(), host.MaxConsecutivePacketsLost.ToString(),
host.RecentlyReceivedPackets.ToString(), PercentToString(host.RecentlyReceivedPacketsPercent),
host.RecentlyLostPackets.ToString(), PercentToString(host.RecentlyLostPacketsPercent),
host.CurrentResponseTime.ToString(), host.AverageResponseTime.ToString("F"),
host.MinResponseTime.ToString(), host.MaxResponseTime.ToString(),
DurationToString(host.CurrentStatusDuration),
DurationToString(host.GetStatusDuration(HostStatus.Alive)),
DurationToString(host.GetStatusDuration(HostStatus.Dead)),
DurationToString(host.GetStatusDuration(HostStatus.DnsError)),
DurationToString(host.GetStatusDuration(HostStatus.Unknown)),
PercentToString(host.HostAvailability),
DurationToString(host.TotalTestDuration),
DurationToString(host.CurrentTestDuration)
});
What I can't seem to figure out is, how to get that data exported to Excel? I am able to export static data to Excel with this code
public static string RunSample1(DirectoryInfo outputDir)
{
if (!outputDir.Exists) throw new Exception("outputDir does not exist!");
FileInfo newFile = new FileInfo(outputDir.FullName + #"\sample1.xlsx");
if (newFile.Exists)
{
newFile.Delete(); // ensures we create a new workbook
newFile = new FileInfo(outputDir.FullName + #"\sample1.xlsx");
}
using (ExcelPackage package = new ExcelPackage(newFile))
{
// add a new worksheet to the empty workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Current Devices");
//Add the headers
//worksheet.Cells[1, 1].Value = "ID";
worksheet.Cells[1, 1].Value = "";
worksheet.Cells[1, 2].Value = "Product";
worksheet.Cells[1, 3].Value = "Quantity";
worksheet.Cells[1, 4].Value = "Price";
worksheet.Cells[1, 5].Value = "Value";
//Add some items...
worksheet.Cells["A2"].Value = 12001;
worksheet.Cells["B2"].Value = "Nails";
worksheet.Cells["C2"].Value = 37;
worksheet.Cells["D2"].Value = 3.99;
What I can't figure out is how to get those listview items in to the spreadsheet cells instead of static data. ListViewItems doesn't seem to yield the properties I would expect. Can someone help me out a bit here?
I found a solution using Microsoft.Office.Interop.Excel instead of trying to use the EPPlus solution.
Related
This question already has answers here:
Download Excel file via AJAX MVC
(15 answers)
How to download excel using ajax call?
(1 answer)
Closed 2 years ago.
I have a list of items from the database base that I will like to generate in excel and PDF. I want to do the excel first. I have not done this before, following a tutorial online I was able to get it to return FIle. But the problem is that I got "non invocable member 'File" cannot be used like a method". I have already used "using System.IO;"
Can someone help figure out what I am doing wrong
{
try
{
//var parameters = new { UserName = username, Password = password };
//var sql = "select * from users where username = #UserName and password = #Password";
//var result = connection.Query(sql, parameters);
IEnumerable<DailyInterest> dailyInterests = null;
var Id = id;
using (var conn = new SqlConnection(connectionstring))
{
await conn.OpenAsync();
//var parameters = new { Id = id };
dailyInterests = conn.Query<DailyInterest>("Select * from DailyInterest where LoanAccountNo=#Id", new { Id = id });
//step1: create array to holder header labels
string[] col_names = new string[]{
"Loan Account No",
"Transaction Amount",
"Interest Rate",
"Interest Amount",
"Original Loan Amount",
"Narration",
"DRCR",
"Transaction Date"
};
//step2: create result byte array
byte[] result;
//step3: create a new package using memory safe structure
using (var package = new ExcelPackage())
{
//step4: create a new worksheet
var worksheet = package.Workbook.Worksheets.Add("final");
//step5: fill in header row
//worksheet.Cells[row,col]. {Style, Value}
for (int i = 0; i < col_names.Length; i++)
{
worksheet.Cells[1, i + 1].Style.Font.Size = 14; //font
worksheet.Cells[1, i + 1].Value = col_names[i]; //value
worksheet.Cells[1, i + 1].Style.Font.Bold = true; //bold
//border the cell
worksheet.Cells[1, i + 1].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
//set background color for each sell
worksheet.Cells[1, i + 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells[1, i + 1].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(255, 243, 214));
}
int row = 8;
//step6: loop through query result and fill in cells
foreach (var item in dailyInterests)
{
for (int col = 1; col <= 2; col++)
{
worksheet.Cells[row, col].Style.Font.Size = 12;
//worksheet.Cells[row, col].Style.Font.Bold = true;
worksheet.Cells[row, col].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
}
//set row,column data
worksheet.Cells[row, 1].Value = item.LoanAccountNo;
worksheet.Cells[row, 2].Value = item.TranAmount;
worksheet.Cells[row, 3].Value = item.InterestRatePerDay;
worksheet.Cells[row, 4].Value = item.AmountPerDay;
worksheet.Cells[row, 5].Value = item.OriginalLoanAmount;
worksheet.Cells[row, 6].Value = item.Narration;
worksheet.Cells[row, 7].Value = item.DRCR;
worksheet.Cells[row, 8].Value = item.TranDate;
//toggle background color
//even row with ribbon style
if (row % 8 == 0)
{
worksheet.Cells[row, 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells[row, 1].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(154, 211, 157));
worksheet.Cells[row, 2].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells[row, 2].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(154, 211, 157));
}
row++;
}
//step7: auto fit columns
worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();
//step8: convert the package as byte array
result = package.GetAsByteArray();
}
//step9: return byte array as a file
**//This is where the error is**
return File(result, "application/vnd.ms-excel", "test.xls");
}
}
catch (Exception ex)
{
throw ex;
}
}
I am trying to convert csv to xls in which there is Bank Account No (16 digit) need to convert it to text
I tried with EPPlus package by which xls is getting generated easily but Bank Account column gets converted to scientific value.Also tried to convert column to numeric and text but thats not working
private void csvToXls(string source,string destination,string fileName)
{
string csvFileName = source;
string excelFileName = destination+"/"+fileName+".xls";
string worksheetsName = "sheet 1";
bool firstRowIsHeader = false;
var format = new ExcelTextFormat();
format.Delimiter = '|';
format.EOL = "\n"; // DEFAULT IS "\r\n";
// format.TextQualifier = '"';
using (ExcelPackage package = new ExcelPackage(new FileInfo(excelFileName)))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(worksheetsName);
worksheet.Cells["A1"].LoadFromText(new FileInfo(csvFileName), format, OfficeOpenXml.Table.TableStyles.None, firstRowIsHeader);
foreach (var cell in worksheet.Cells["C:C"])
{
cell.Value = Convert.ToString(cell.Value);
}
foreach (var cell in worksheet.Cells["AC:AC"])
{
cell.Value = Convert.ToString(cell.Value);
}
worksheet.Cells["C:C"].Style.Numberformat.Format = "#0";
worksheet.Cells["C:C"].Style.Numberformat.Format = "#";
worksheet.Cells["AC:AC"].Style.Numberformat.Format = "#";
package.Save();
}
}
Need to convert columns to text which should not be scientific value.Please suggest
Input : In test.csv below input is there
IMDATA||12345678910124567895274|1|NAME|||||||||TEST|||||||||||TESTING||||3301003726558|TDATASTING|TESTING|27-09-2019
Getting Output :
Expected Output :
You need to provide eDataTypes to LoadFromText method for each column, if no types provide for the column it will set to the General by default
So, provide the `eDataTypes to ExcelTextFormat.
I just added for 3 columns and its worked well.
public static void csvToXls(string source, string destination, string fileName)
{
string csvFileName = source;
string excelFileName = destination + "/" + fileName + ".xls";
string worksheetsName = "sheet 1";
bool firstRowIsHeader = false;
var format = new ExcelTextFormat();
var edataTypes = new eDataTypes[] { eDataTypes.String, eDataTypes.String, eDataTypes.String };
format.DataTypes = edataTypes;
format.Delimiter = '|';
format.EOL = "\n"; // DEFAULT IS "\r\n";
// format.TextQualifier = '"';
using (ExcelPackage package = new ExcelPackage(new FileInfo(excelFileName)))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(worksheetsName);
worksheet.Cells["A1"].LoadFromText(new FileInfo(csvFileName), format, OfficeOpenXml.Table.TableStyles.None, firstRowIsHeader);
package.Save();
}
}
OR
You can try to read the text manually
public static void csvToXls(string source, string destination, string fileName)
{
string csvFileName = source;
string excelFileName = destination + "/" + fileName + ".xls";
string worksheetsName = "sheet 1";
using (ExcelPackage package = new ExcelPackage(new FileInfo(excelFileName)))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(worksheetsName);
var text = File.ReadAllText(source);
var rows = text.Split('\n');
for (int rowIndex = 0; rowIndex < rows.Length; rowIndex++)
{
var excelRow = worksheet.Row(rowIndex+1);
var columns = rows[rowIndex].Split('|');
for (int colIndex = 0; colIndex < columns.Length; colIndex++)
{
worksheet.Cells[rowIndex +1, colIndex +1].Value = columns[colIndex];
}
}
package.Save();
}
}
How to sort a PivotTable with Interop.Excel and C#?
I got the generation of the PivotTable fully like I want it to, but struggling with the sorting...
Sorting should be done, that for "Title" and "SubTitle" the fields "Value2" are always having the highest descending values at the top per project.
Was trying around via Range.Sort() but without luck.
Tested way:
Defining a region (like I did manually in Excel for figuring out the way) with "C4" and the doing a Range.Sort on this. But then it is working for the first project, but not for all. Imho, because I set this only to the pointed range to one cell. The next try was to extend the range, but then I always got HRESULT exceptions with just an memory address given (useless for me).
The screenshots are showing the wanted sorting.
public void GeneratePivot()
{
const string numberFormat = "#,##0 €;-#,##0 €";
var missing = Type.Missing;
string dataContext = #"DataContext";
#region // Create Data
var dt = new DataTable();
dt.Columns.Add(new DataColumn() { ColumnName = "Project", DataType = typeof(string) });
dt.Columns.Add(new DataColumn() { ColumnName = "Title", DataType = typeof(string) });
dt.Columns.Add(new DataColumn() { ColumnName = "SubTitle", DataType = typeof(string) });
dt.Columns.Add(new DataColumn() { ColumnName = "Value1", DataType = typeof(decimal) });
dt.Columns.Add(new DataColumn() { ColumnName = "Value2", DataType = typeof(decimal) });
var row1 = dt.NewRow();
row1["Project"] = "Project1";
row1["Title"] = "Title1";
row1["SubTitle"] = "SubTitle1-1";
row1["Value1"] = 1000M;
row1["Value2"] = 40000M;
dt.Rows.Add(row1);
var row2 = dt.NewRow();
row2["Project"] = "Project2-1";
row2["Title"] = "Title2";
row2["SubTitle"] = "SubTitle2-1";
row2["Value1"] = 100M;
row2["Value2"] = 4000M;
dt.Rows.Add(row2);
var row3 = dt.NewRow();
row3["Project"] = "Project2-2";
row3["Title"] = "Title2";
row3["SubTitle"] = "SubTitle2-2";
row3["Value1"] = 220M;
row3["Value2"] = 222000M;
dt.Rows.Add(row3);
var row4 = dt.NewRow();
row4["Project"] = "Project3-1";
row4["Title"] = "Title3";
row4["SubTitle"] = "SubTitle3-1";
row4["Value1"] = 32423M;
row4["Value2"] = 430M;
dt.Rows.Add(row4);
var row5 = dt.NewRow();
row5["Project"] = "Project3-2";
row5["Title"] = "Title3";
row5["SubTitle"] = "SubTitle3-2";
row5["Value1"] = 2341M;
row5["Value2"] = 4002000M;
dt.Rows.Add(row5);
#endregion
// Create Workbook with Excel Interop
Excel.Application excelApplication = new Excel.Application();
Excel.Workbooks workbooks = excelApplication.Workbooks;
var workbook = workbooks.Add();
#region // Create DataSheet
Excel.Worksheet worksheet1 = workbook.Sheets[1];
worksheet1.Name = "DataSheet";
var colsCount = dt.Columns.Count;
var rowsCount = dt.Rows.Count;
Excel.Range range;
// Create DataArray from DataTable
object[,] dtArray = new object[rowsCount, colsCount];
for (int i = 0; i < rowsCount; i++)
{
for (int j = 0; j < colsCount; j++) { dtArray[i, j] = dt.Rows[i][j]; }
}
// Create header
range = worksheet1.Cells[1, 1];
range = range.get_Resize(1, colsCount);
range.NumberFormat = "#";
range.Font.Bold = true;
range.Value = new string[5] { "Project", "Title", "SubTitle", "Value1", "Value2" };
// Get an Excel Range of the same dimensions
range = (Excel.Range)worksheet1.Cells[2, 1];
range = range.get_Resize(rowsCount, colsCount);
// Assign the 2-d array to the Excel Range
range.set_Value(Excel.XlRangeValueDataType.xlRangeValueDefault, dtArray);
range = worksheet1.UsedRange;
worksheet1.Names.Add("DataContext", range);
#endregion
#region // Create PivotSheet
Excel.Worksheet worksheet2 = workbook.Sheets.Add(After: workbook.Sheets[workbook.Sheets.Count]);
worksheet2.Name = "PivotSheet";
Excel.PivotCache pivotCache;
Excel.PivotTable pivotTable;
Excel.Range pivotData;
Excel.Range pivotDestination;
// Select a range of data for the Pivot Table.
pivotData = worksheet1.get_Range(dataContext);
// Select location of the Pivot Table.
pivotDestination = worksheet2.get_Range("A1", missing);
// create Pivot Cache and Pivot Table
pivotCache = (Excel.PivotCache)workbook.PivotCaches()
.Add(Excel.XlPivotTableSourceType.xlDatabase, pivotData);
pivotTable = (Excel.PivotTable)worksheet2.PivotTables()
.Add(PivotCache: pivotCache, TableDestination: pivotDestination, TableName: dataContext);
// Style Pivot Table
pivotTable.Format(Excel.XlPivotFormatType.xlReport2);
pivotTable.InGridDropZones = false;
pivotTable.SmallGrid = false;
pivotTable.TableStyle2 = "PivotStyleLight16";
// ROW FIELDS
Excel.PivotField rowField3 = (Excel.PivotField)pivotTable.PivotFields("SubTitle");
rowField3.Orientation = Excel.XlPivotFieldOrientation.xlRowField;
rowField3.LayoutForm = Excel.XlLayoutFormType.xlOutline;
rowField3.LayoutSubtotalLocation = Excel.XlSubtototalLocationType.xlAtTop;
rowField3.LayoutCompactRow = true;
Excel.PivotField rowField2 = (Excel.PivotField)pivotTable.PivotFields("Title");
rowField2.Orientation = Excel.XlPivotFieldOrientation.xlRowField;
rowField2.LayoutForm = Excel.XlLayoutFormType.xlOutline;
rowField2.LayoutSubtotalLocation = Excel.XlSubtototalLocationType.xlAtTop;
rowField2.LayoutCompactRow = true;
Excel.PivotField rowField1 = (Excel.PivotField)pivotTable.PivotFields("Project");
rowField1.Orientation = Excel.XlPivotFieldOrientation.xlRowField;
rowField1.LayoutForm = Excel.XlLayoutFormType.xlOutline;
rowField1.LayoutSubtotalLocation = Excel.XlSubtototalLocationType.xlAtTop;
rowField1.LayoutCompactRow = true;
// FILTER FIELDS
Excel.PivotField pageField1 = (Excel.PivotField)pivotTable.PivotFields("Project");
pageField1.Orientation = Excel.XlPivotFieldOrientation.xlPageField;
pageField1.EnableMultiplePageItems = true;
// DATA FIELDS
int position = 1;
Excel.PivotField dataField1 = (Excel.PivotField)pivotTable.PivotFields("Value1");
dataField1.Orientation = Excel.XlPivotFieldOrientation.xlDataField;
dataField1.Function = Excel.XlConsolidationFunction.xlSum;
dataField1.NumberFormat = numberFormat;
dataField1.Position = position++;
Excel.PivotField dataField2 = (Excel.PivotField)pivotTable.PivotFields("Value2");
dataField2.Orientation = Excel.XlPivotFieldOrientation.xlDataField;
dataField2.Function = Excel.XlConsolidationFunction.xlSum;
dataField2.NumberFormat = numberFormat;
dataField2.Position = position++;
#endregion
// Close Excel
workbook.SaveAs("Interop.Excel_Pivot.xlsx");
workbook.Close();
excelApplication.Quit();
}
This did it!
var pivotLine = (Excel.PivotLine)pivotTable.PivotColumnAxis.PivotLines[2];
rowField2.AutoSortEx((int)Excel.XlSortOrder.xlDescending, "Summe von Value2", pivotLine, 1);
rowField3.AutoSortEx((int)Excel.XlSortOrder.xlDescending, "Summe von Value2", pivotLine, 1);
Hint: Beware of, that given String "Summe von " is german language and will be "Sum of " with Excel in English. ;)
I use the following Code:
using (var package = new ExcelPackage()) {
var worksheet = package.Workbook.Worksheets.Add("Test");
var cell = worksheet.Cells[1, 1];
var r1 = cell.RichText.Add("TextLine1" + "\r\n");
r1.Bold = true;
var r2 = cell.RichText.Add("TextLine2" + "\r\n");
r2.Bold = false;
package.SaveAs(...);
}
But in the Excel file the newLines are gone...
I tried also with "\n" and "\r" but nothing was working...
Finally I found the solution. Here is a working sample:
using (var package = new ExcelPackage(fileInfo)) {
var worksheet = package.Workbook.Worksheets.Add("Test");
var cell = worksheet.Cells[1, 1];
cell.Style.WrapText = true;
cell.Style.VerticalAlignment = ExcelVerticalAlignment.Top;
var r1 = cell.RichText.Add("TextLine1" + "\r\n");
r1.Bold = true;
var r2 = cell.RichText.Add("TextLine2" + "\r\n");
r2.Bold = false;
package.Save();
}
But I think I found a bug in the Lib: This Code is NOT working:
using (var package = new ExcelPackage(fileInfo)) {
var worksheet = package.Workbook.Worksheets.Add("Test");
var cell = worksheet.Cells[1, 1];
cell.Style.WrapText = true;
cell.Style.VerticalAlignment = ExcelVerticalAlignment.Top;
var r1 = cell.RichText.Add("TextLine1" + "\r\n");
r1.Bold = true;
var r2 = cell.RichText.Add("TextLine2" + "\r\n");
r2.Bold = false;
cell = worksheet.Cells[1, 1];
var r4 = cell.RichText.Add("TextLine3" + "\r\n");
r4.Bold = true;
package.Save();
}
When I get the same range again and add new RichText Tokens, the old LineBreaks are deleted... (They are actually converted to "\n" and this is not working in Excel.)
The Encoding of new line in excel cell is 10.
I think you have to do someihing like thise:
var r1 = cell.RichText.Add("TextLine1" + ((char)10).ToString());
using (var package = new ExcelPackage(fileInfo)) {
var worksheet = package.Workbook.Worksheets.Add("Test");
var cell = worksheet.Cells[1, 1];
cell.Style.WrapText = true;
cell.Style.VerticalAlignment = ExcelVerticalAlignment.Top;
var r1 = cell.RichText.Add("TextLine1" + "\n\n");
r1.Bold = true;
var r2 = cell.RichText.Add("TextLine2" + "\n\n");
r2.Bold = false;
package.Save();
}
There are some sheets which is created from a XML file.
There are some names in 2nd sheet .excel is created by reading XML file and change it to data-set and later created worksheet and all other rows and columns with the help of OPEN-XML .
So I want to create a list using names from 2nd sheet and show the list in sheet 1 as drop-down.Using OPEN-XML I want to create a drop-downlist with data taken from 2nd page. I browse many time but i did not find any solution Is it possible to create dropdown using openxml.
This is my whole code for creating excel from xml file so if it have solution please help me.
public void ExportDSToExcel(DataSet ds, string dest)
{
try
{
using (var workbook = SpreadsheetDocument.Create(dest, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
{
var workbookPart = workbook.AddWorkbookPart();
workbook.WorkbookPart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();
workbook.WorkbookPart.Workbook.Sheets = new DocumentFormat.OpenXml.Spreadsheet.Sheets();
uint sheetId = 1;
foreach (DataTable table in ds.Tables)
{
var sheetPart = workbook.WorkbookPart.AddNewPart<WorksheetPart>();
var sheetData = new DocumentFormat.OpenXml.Spreadsheet.SheetData();
sheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(sheetData);
DocumentFormat.OpenXml.Spreadsheet.Sheets sheets = workbook.WorkbookPart.Workbook.GetFirstChild<DocumentFormat.OpenXml.Spreadsheet.Sheets>();
string relationshipId = workbook.WorkbookPart.GetIdOfPart(sheetPart);
if (sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Count() > 0)
{
sheetId =
sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Select(s => s.SheetId.Value).Max() + 1;
}
DocumentFormat.OpenXml.Spreadsheet.Sheet sheet = new DocumentFormat.OpenXml.Spreadsheet.Sheet()
{
Id = relationshipId, SheetId = sheetId, Name = table.TableName
};
sheets.Append(sheet);
if(sheet.Name=="Customer")
{
PageMargins pageM = sheetPart.Worksheet.GetFirstChild<PageMargins>();
SheetProtection sheetProtection = new SheetProtection();
sheetProtection.Password = "admin";
sheetProtection.Sheet = true;
sheetProtection.Objects = true;
sheetProtection.Scenarios = true;
ProtectedRanges pRanges = new ProtectedRanges();
ProtectedRange pRange = new ProtectedRange();
ListValue<StringValue> lValue = new ListValue<StringValue>();
lValue.InnerText = ""; //set cell which you want to make it editable
pRange.SequenceOfReferences = lValue;
pRange.Name = "not allow editing";
pRanges.Append(pRange);
sheetPart.Worksheet.InsertBefore(sheetProtection, pageM);
sheetPart.Worksheet.InsertBefore(pRanges, pageM);
if (cell.CellReference == "B4")
{
CellFormula cellformula = new CellFormula();
cellformula.Text = "=INDEX(Sheet5!B:B,MATCH(A4,Sheet5!B:B,0))";
CellValue cellValue = new CellValue();
cellValue.Text = "0";
cell.Append(cellformula);
cell.Append(cellValue);
}
}
DocumentFormat.OpenXml.Spreadsheet.Row headerRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
if (RadioButtonList1.SelectedItem.Text == "Yes")
{
PageMargins pageM = sheetPart.Worksheet.GetFirstChild<PageMargins>();
SheetProtection sheetProtection = new SheetProtection();
sheetProtection.Password = "admin";
sheetProtection.Sheet = true;
sheetProtection.Objects = true;
sheetProtection.Scenarios = true;
ProtectedRanges pRanges = new ProtectedRanges();
ProtectedRange pRange = new ProtectedRange();
ListValue<StringValue> lValue = new ListValue<StringValue>();
lValue.InnerText = ""; //set cell which you want to make it editable
pRange.SequenceOfReferences = lValue;
pRange.Name = "not allow editing";
pRanges.Append(pRange);
sheetPart.Worksheet.InsertBefore(sheetProtection, pageM);
sheetPart.Worksheet.InsertBefore(pRanges, pageM);
}
else
{
}
List<String> columns = new List<string>();
foreach (DataColumn column in table.Columns)
{
columns.Add(column.ColumnName);
DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(column.ColumnName);
headerRow.AppendChild(cell);
}
sheetData.AppendChild(headerRow);
foreach (DataRow dsrow in table.Rows)
{
DocumentFormat.OpenXml.Spreadsheet.Row newRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
foreach (String col in columns)
{
DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(dsrow[col].ToString()); //
newRow.AppendChild(cell);
}
sheetData.AppendChild(newRow);
}
}
}
}
catch
{
lblstatus.Text = "File Upload Not Succesfull ";
}
lblstatus.Text = "File Upload Succesfull ";
}
protected void Button1_Click(object sender, EventArgs e)
{
if(txtname.Text != null)
{
if (FileUpload1.HasFile == true)
{
string myXMLfile = "/uploads/" + FileUpload1.FileName;
FileUpload1.SaveAs(Server.MapPath(myXMLfile));
string dest = "D:/uploads/" + txtname.Text+".xlsx";
DataSet ds = new DataSet();
try
{
ds.ReadXml(Server.MapPath(myXMLfile));
}
catch (Exception ex)
{
lblstatus.Text=(ex.ToString());
}
ExportDSToExcel(ds, dest);
}
else
{
lblstatus.Text = "Please Upload the file ";
}
}
else {
lblstatus.Text = "Please enter the name ";
}
}
}
You need create a Validator
First Parameter is a worksheet where create a dropdown
Second parameter is worksheet to take data from
A1:A1048576 - is a cells to apply this Validator
public void CreateValidator(Worksheet ws, string dataContainingSheet)
{
/*** DATA VALIDATION CODE ***/
DataValidations dataValidations = new DataValidations();
DataValidation dataValidation = new DataValidation
{
Type = DataValidationValues.List,
AllowBlank = true,
SequenceOfReferences = new ListValue<StringValue> { InnerText = "A1:A1048576" }
};
dataValidation.Append(
//new Formula1 { Text = "\"FirstChoice,SecondChoice,ThirdChoice\"" }
new Formula1(string.Format("'{0}'!$A:$A", dataContainingSheet))
);
dataValidations.Append(dataValidation);
var wsp = ws.WorksheetPart;
wsp.Worksheet.AppendChild(dataValidations);
}