Archive for category ThirdParty Tools

How to display larger numbers on Excel export in C#

Introduction:

In this article I am going to explain a solution to the problem with displaying large numbers (more than 15 numbers) in excel while exporting data in C#.

Issue Description:

By default, excel normally display larger numbers like 123456E+17 when the number overcomes Excel’s precision limit for numbers which is 8 digits. When we export the data from Gridivew to excel the same problem exists.

Excel

Drawback of existing Solution:

One solution to resolve this is to make the column type of excel to text instead of numbers. To this we need to add a single quote (‘) to the numbers which we are exporting. This will resolve the issue of displaying the complete number, however this solution has a drawback as it will display single quote along with the number like ‘123456789011.

Solution to the Problem

To show the number without using single quote we can use a Third Party Excel library called EPPlus. EPPlus is a .net library that reads and writes Excel 2007/2010 files using the Open Office Xml format (xlsx). This library offers several features and methods to help the user to generate Excel sheet. You can read the complete details from the link I shared above.

Here in this fix we will use the method LoadFromDataTable to load the data from DataTable to Excel. The same case applies when you Export data from gridview and other controls.

Code

private void ExcelExport(DataTable tbl)
        {
            using (ExcelPackage pck = new ExcelPackage())
            {
                //Create the worksheet
                ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");
                //Load the datatable into the sheet, starting from cell A1.
                ws.Cells["A1"].LoadFromDataTable(tbl, true);
                //Write it back to the client
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("content-disposition", "attachment;filename=file.xlsx");
                Response.BinaryWrite(pck.GetAsByteArray());
            }
        }

Before using above code add the below references in your page

using OfficeOpenXml;
using OfficeOpenXml.Style;

Sample usage to above method

DataTable dt = new DataTable();
            dt.Columns.Add("PhoneNo");
            dt.Columns.Add("Name");
            DataRow Sample = dt.NewRow();
            Sample["PhoneNo"] = "12345678911121314";
            Sample["Name"] = "SampleName";
            dt.Rows.Add(Sample);
            ExcelExport(dt);

With above code the exported excel file will look like below

Excel2

You can use Nugget to add the EPPlus in your solution.

 

, , , , , , ,

1 Comment

How to Crop the Image using CropImage.Net tool in Asp.Net

Introduction:

In this article I am going to explain how to crop an Image using CropImage.Net

Prerequisites:

You can download the dll files needed to use CropImage.Net from this link. Once you have a downloaded the files you need to add the dll files to your solution. You can follow the below steps to add the dlls.

  • Open your Project within the Solution Explorer
  • Right-click the References folder and Choose Add Reference options
  • Find and select the dlls which needs to be added to your solution
    • ImageResizer.dll
    • Imazen.Crop.dll
    • System.Web.Extensions.dll (You may need to use the browse button if you are not finding the dll in available list)
  • Click the Ok button to add it to your Project.

Now you have all the files added to your project

Details of CropImage.Net Control:

CropImage.Net exposes method called Crop, which actually Crops the original image and saves it to the specified path. This method have two overrides one with destinationpath as parameter and another one with destinationpath and appendCorrectExtension.

public void Crop(string destPath);
public void Crop(string destPath, bool appendCorrectExtension)

 Implementation:

Here I am going to explain the steps on how to use CropImage.Net tool to crop the images using Asp.Net.

In this demo I will upload a file and then the uploaded file will be shown in an image control. Then with the help of CropImage control the image will be cropped and shown in another image control called result.

First Step is to register the ImageCrop control in your page like given below

<%@ Register Assembly="Imazen.Crop" Namespace="Imazen.Crop" TagPrefix="ic" %>

Then you need add the below CropImage control to your page and then set it Image property to the Image control from which Image is used to crop.

<ic:CropImage ID="CropImage1" runat="server" Image="Image1" CanvasWidth="300" />

Then we use the Crop method to crop and save the image to the destination path provided.

//Save the copy in local folder
CropImage1.Crop(MapPath("~/images"), true);

You also need to add the below configurations to your webconfig file

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" />
    <httpModules>
      <add name="ImageResizingModule" type="ImageResizer.InterceptModule"/>
    </httpModules>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules>
      <add name="ImageResizingModule" type="ImageResizer.InterceptModule"/>
    </modules>
  </system.webServer>
</configuration>

Complete Code:

HTML:

<%@ Register Assembly="Imazen.Crop" Namespace="Imazen.Crop" TagPrefix="ic" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <h3>Croping Image using ImageResizer in .Net</h3>
            <asp:FileUpload ID="FileUpload1" runat="server" />
            <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
            <asp:Image ID="Image1" runat="server" ImageUrl="" />
            

            <ic:CropImage ID="CropImage1" runat="server" Image="Image1" CanvasWidth="300" />
            

            <asp:Button ID="Button1" runat="server" Text="Crop" OnClick="btnCrop_Click" />
            <h3>The result</h3>
            <asp:Image ID="Result" runat="server" Visible="false" />
        </div>
    </form>
</body>
</html>

C#:

protected void btnCrop_Click(object sender, EventArgs e)
    {

        //Show the Result Image control 
        Result.Visible = true;
        //Assign the image url from CropImage control
        Result.ImageUrl = CropImage1.CroppedUrl;

        //Save the copy in local folder
        CropImage1.Crop(MapPath("~/images"), true);

        //You can also get the coordinates from CropImage if you want to show to the user
        this.Title = CropImage1.X + "," + CropImage1.Y + "," + CropImage1.X2 + "," + CropImage1.Y2;

    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        //Check if file upload is having any value
        if (FileUpload1.HasFile)
        {
            try
            {
                //Get the uploaded filename from FileUpload Control
                string filename = System.IO.Path.GetFileName(FileUpload1.FileName);
                //Save the file to folder
                FileUpload1.SaveAs(Server.MapPath("~/images/") + filename);
                //Show the uploaded image in Image Control which is tagged to the Image Cropping Control
                Image1.ImageUrl = "~/images/" + filename;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.InnerException.ToString());
            }
        }
    }

Note that I have used the folder which is inside in my solution.You can see that in the image given above. If you have a different you need to change the path accordingly.

Demo

, , , , ,

3 Comments