How to add dropdown in excel sheet programmatically? - asp.net

I am using the ExcelPackage dll to creating the excel from the .net application.
I want to add drop down list in one of column of Excel sheet. How to add it?
Also I want to do some formatting changes to the cell values.

Try spreadsheetgear
....

protected void AddDropDownToExcel(string path)
{
//path gives the location where u have created excel file
string fileName = path.Replace("\\", "\\\\");
// F is the column name where you want to place the dropdown
string RowCount = "F" + gridrowcount;
// Open Excel and get first worksheet.
var workbook = application.Workbooks.Open(fileName);
var worksheet = workbook.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet;
// Set range for dropdownlist
var rangeNewStatus = worksheet.get_Range("F2", RowCount);
rangeNewStatus.ColumnWidth = 20;
rangeNewStatus.Validation.Add(Microsoft.Office.Interop.Excel.XlDVType.xlValidateList, Microsoft.Office.Interop.Excel.XlDVAlertStyle.xlValidAlertStop,
Microsoft.Office.Interop.Excel.XlFormatConditionOperator.xlBetween, "dropdownlistitem1, dropdownlistitem2");
// Save.
workbook.Save();
workbook.Close(Microsoft.Office.Interop.Excel.XlSaveAction.xlSaveChanges, Type.Missing, Type.Missing);
application.Quit();
}

Related

How to add field to a Shapefile using DotSpatial?

I tried searching the web to find a sample of showing how to add a Field to attribute table of an existing shapefile. For example I have a Shapefile at
C://data/Streets.shp
and need to add two field L_CITY and R_CITY both text and 50 characters limit. How can I do this in DotSpatial?
The first thing you need to do is add a reference to System.Data. Otherwise, the type definition for the DataTable is not available and it may not be obvious what you can do to modify the schema.
Then you can use standard DataTable programming like the following code:
public void AddFieldExample()
{
IFeatureSet fs = FeatureSet.OpenFile("C:\\YourShapefile.shp");
DataTable table = fs.DataTable;
DataColumn lCity = table.Columns.Add("L_CITY");
lCity.MaxLength = 50;
DataColumn rCity = table.Columns.Add("R_CITY");
rCity.MaxLength = 50;
}

asp.net OpenXML insert data to cell

I've been following this guide https://msdn.microsoft.com/EN-US/library/office/cc861607.aspx to insert a string to a cell in an excel file. The example is really confusing, and even when i copy/paste it doesn't work. I'm looking for a very simple example to insert a a value into a cell like:
spredSheet.InsertCell("A", 1, string value)
I could really use a simple code example showing me how to insert data into a cell using OpenXML in asp.net.
I tried the code from this post Using OpenXML to insert a datatable into excel, but it creates a broken excel file.
This is how my code look without the helper functions from the link
using (SpreadsheetDocument myDoc = SpreadsheetDocument.
Create(Server.MapPath("/data.xls"), SpreadsheetDocumentType.Workbook))
{
WorkbookPart workbookpart = myDoc.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
// Add a WorksheetPart to the WorkbookPart.
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
//add column names to the first row
Row header = new Row();
header.RowIndex = (UInt32)1;
SheetData sheetData = new SheetData();
Cell headerCell = createTextCell(1, 1, text);
header.AppendChild(headerCell);
sheetData.AppendChild(header);
// Add a WorkbookPart to the document.
worksheetPart.Worksheet = new Worksheet(sheetData);
}
The MSDN example is using SpreadsheetDocument.Open which opens an existing file but you are creating a brand new file with SpreadsheetDocument.Create. When you create a brand new file there are certain elements you must create in order for the file to be valid. The elements you are missing are the Sheets and Sheet elements.
Sheets are stored separately from the SheetData so you need to create a Sheet inside a Sheets and then associate the Sheets with the WorksheetPart.
This can be done like so:
Sheets sheets = myDoc.WorkbookPart.Workbook.AppendChild(new Sheets());
sheets.AppendChild(new Sheet()
{
Id = myDoc.WorkbookPart.GetIdOfPart(myDoc.WorkbookPart.WorksheetParts.First()),
SheetId = 1,
Name = "Sheet1"
});
So your full code listing would be something like:
using (SpreadsheetDocument myDoc = SpreadsheetDocument.
Create(Server.MapPath("/data.xls"), SpreadsheetDocumentType.Workbook))
{
WorkbookPart workbookpart = myDoc.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
// Add a WorksheetPart to the WorkbookPart.
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
//add column names to the first row
Row header = new Row();
header.RowIndex = (UInt32)1;
SheetData sheetData = new SheetData();
Cell headerCell = createTextCell(1, 1, text);
header.AppendChild(headerCell);
sheetData.AppendChild(header);
// Add a WorkbookPart to the document.
worksheetPart.Worksheet = new Worksheet(sheetData);
//this is the part that was missing from your code
Sheets sheets = myDoc.WorkbookPart.Workbook.AppendChild(new Sheets());
sheets.AppendChild(new Sheet()
{
Id = myDoc.WorkbookPart.GetIdOfPart(myDoc.WorkbookPart.WorksheetParts.First()),
SheetId = 1,
Name = "Sheet1"
});
}

Populate a 2 dimensional List From Directory.GetFiles

I currently am populating a dropdown list with the contents of all files in a directory using this code:
string[] filePaths = Directory.GetFiles(#ConfigurationManager.AppSettings["File_Path"]
.ToString(), "*.txt");
if (filePaths == null || filePaths.Length == 0)
{
ddlFiles.Items.Insert(0, new ListItem("NO TEXT FILES CURRENTLY AVAILABLE !"));
}
else
{
ddlFiles.DataSource = filePaths;
ddlFiles.DataBind();
ddlFiles.Items.Insert(0, new ListItem("PLEASE SELECT A TEXT FILE"));
}
The problem is that the dropdown will show the complete path to the files. I just want to show the file name and extension. I figure that I could use a two dimensional List, and load the path into one dimension. I could then just loop through that dimension and parse everything after the last "\" to get just the file name and write it back to the other dimension in that List. This would result in a List with two dimensions, one with paths and one with file names. I could then load the dropdown from the 2 dimensional List using the path for the DataValueField and the file name for the DataTextField.
My problem is that I can't get a 2 Dimensional List to load from Directory.GetFiles. Can someone post an example?
Also, how do I specifically address each dimension in the List to load the Value/Text attributes of the dropdown list?
Thank You in advance for your help!
I don't think you need multi-dimensional arrays here.. You can just separate "Value" and "Text". That is, data binding supports value and text, using "DataValueField" and "DataTextField", you could just use those. Means, first you get a list of pairs, and then bind them to the value/text of the item, like this:
var filePaths = Directory.GetFiles(#ConfigurationManager.AppSettings["File_Path"].ToString(), "*.txt")
.Select(path => new
{
Path = path,
Name = Path.GetFileName(path)
}).ToArray();
if (filePaths == null || filePaths.Length == 0)
{
ddlFiles.Items.Insert(0, new ListItem("NO TEXT FILES CURRENTLY AVAILABLE !"));
}
else
{
ddlFiles.DataSource = filePaths;
ddlFiles.DataValueField = "Path";
ddlFiles.DataTextField = "Name";
ddlFiles.DataBind();
ddlFiles.Items.Insert(0, new ListItem("PLEASE SELECT A TEXT FILE"));
}

To change the metatags of PNG Image files

I am using PngCs dll to fetch the chunk data for Png image file in asp.net, I am able to do that but now I want to update the chunk data for that PNG.
I used PngWriter but it is creating whole new file without inheriting chunk data.
PngReader pngr = FileHelper.CreatePngReader(path);
pngr.GetMetadata().GetTxtForKey(PngChunkITXT.KEY_Title);
Response.Write(pngr.GetMetadata().GetTxtForKey(PngChunkITXT.KEY_Title));
Below code is for writing new Png Image through PngWriter ,I want embed new itxt chunk while creating new file.
PngReader pngr = FileHelper.CreatePngReader(origFilename); // or you can use the constructor
PngWriter pngw = FileHelper.CreatePngWriter(destFilename, pngr.ImgInfo, true); // idem
Console.WriteLine(pngr.ToString()); // just information
int chunkBehav = ChunkCopyBehaviour.COPY_ALL_SAFE; // tell to copy all 'safe' chunks
pngw.CopyChunksFirst(pngr, chunkBehav); // copy some metadata from reader
for (int row = 0; row < pngr.ImgInfo.Rows; row++)
{
ImageLine l1 = pngr.ReadRowInt(row); // format: RGBRGB... or RGBARGBA...
pngw.WriteRow(l1, row);
}
pngw.CopyChunksLast(pngr, chunkBehav); // metadata after the image pixels? can happen
pngw.End(); // dont forget this
pngr.End();
for further reference click this link
Try this
PngReader pngr = FileHelper.CreatePngReader(origFilename);
PngWriter pngw = FileHelper.CreatePngWriter(destFilename, pngr.ImgInfo, true);
pngw.CopyChunksFirst(pngr, ChunkCopyBehaviour.COPY_ALL);
pngw.GetMetadata().SetText(myKey, myText,false,false); // provide your own data
for (int row = 0; row < pngr.ImgInfo.Rows; row++) {
ImageLine l1 = pngr.ReadRowInt(row);
pngw.WriteRow(l1, row);
}
pngw.CopyChunksLast(pngr, ChunkCopyBehaviour.COPY_ALL);
pngw.End(); // dont forget this
pngr.End();
the problem has been solved by using CsXMpToolKit.dll ,which is the best option to fetch the metadat from any type of file.

bulk insertion in MS SQL from a text file

I have a text file that contains around 21 lac entries and I want to insert all these entries into a table. Initially I have created one function in c# that read line by line and insert into table but it takes too much time. Please suggest an efficient way to insert these bulk data and that file is containing TAB(4 spaces) as delimiter.
And that text file also containing some duplicate entries and I don't want to insert those entries.
Load all of your data into a DataTable object and then use SqlBulkCopy to bulk insert them:
DataTable dtData = new DataTable("Data");
// load your data here
using (SqlConnection dbConn = new SqlConnection("db conn string"))
{
dbConn.Open();
using (SqlTransaction dbTrans = dbConn.BeginTransaction())
{
try
{
using (SqlBulkCopy dbBulkCopy = new SqlBulkCopy(dbConn, SqlBulkCopyOptions.Default, dbTrans))
{
dbBulkCopy.DestinationTableName = "intended SQL table name";
dbBulkCopy.WriteToServer(dtData );
}
dbTrans.Commit();
}
catch
{
dbTrans.Rollback();
throw;
}
}
dbConn.Close();
}
I've included the example to wrap this into a SqlTransaction so there will be a full rollback if there's a failure along the way. To get you started, here's a good CodeProject article on loading the delimited data into a DataSet object.
Sanitizing the data before loading
OK, here's how I think your data looks:
CC_FIPS FULL_NAME_ND
AN Xixerella
AN Vila
AN Sornas
AN Soldeu
AN Sispony
... (cut down for brevity)
In this instance you want to create your DataTable like this:
DataTable dtData = new DataTable("Data");
dtData.Columns.Add("CC_FIPS");
dtData.Columns.Add("FULL_NAME_ND");
Then you want to iterate each row (assuming your tab delimited data is separated row-by-row by carriage returns) and check whether this data already exists in the DataTable using the .Select method and if there is a match (i'm checking for BOTH values, it's up to you whether you want to do something else) then don't add it thereby preventing duplicates.
using (FileStream fs = new FileStream("path to your file", FileMode.Open, FileAccess.Read))
{
int rowIndex = 0;
using (StreamReader sr = new StreamReader(fs))
{
string line = string.Empty;
while (!sr.EndOfStream)
{
line = sr.ReadLine();
// use a row index to skip the header row as you don't want to insert CC_FIPS and FULL_NAME_ND
if (rowIndex > 0)
{
// split your data up into a 2-d array tab delimited
string[] parts = line.Split('\t');
// now check whether this data has already been added to the datatable
DataRow[] rows = dtData.Select("CC_FIPS = '" + parts[0] + "' and FULL_NAME_ND = '" + parts[1] + "'");
if (rows.Length == 0)
{
// if there're no rows, then the data doesn't exist so add it
DataRow nr = dtData.NewRow();
nr["CC_FIPS"] = parts[0];
nr["FULL_NAME_ND"] = parts[1];
dtData.Rows.Add(nr);
}
}
rowIndex++;
}
}
}
At the end of this you should have a sanitized DataTable that you can bulk insert. Please note that this code isn't tested, but it's a best guess as to how you should do it. There are many ways this can be done, and probably a lot better than this method (specifically LINQ) - but it's a starting point.

Resources