I want to extract some data in the datatable, and want to send the email.
But when I extract the data, excel has many blanks between the extracted data.
The data which is not extracted make a blank row.
When I try to use RemoveRow() function, it doesn't work and still has a blank row.
private void Email()
{
//get the data from database
DataTable data = GetData();
int maxLavel = Convert.ToInt32(data.Compute("max([AssignedID])", string.Empty));
IWorkbook workbook;
workbook = new HSSFWorkbook();
for (int Emp = 0; Emp < maxLavel; Emp++)
{
ISheet sheet1 = workbook.CreateSheet("Sheet 1");
int num = 0;
//make a header row
IRow row1 = sheet1.CreateRow(0);
for (int j = 0; j < data.Columns.Count; j++)
{
ICell cell = row1.CreateCell(j);
String columnName = data.Columns[j].ToString();
cell.SetCellValue(columnName);
}
//loops through data
for (int i = 0; i < data.Rows.Count; i++)
{
IRow row = sheet1.CreateRow(i + 1);
if (Emp == Convert.ToInt32(data.Rows[i][0]))
{
num++;
ICell cell = row.CreateCell(j);
for (int j = 0; j < data.Columns.Count; j++)
{
sheet1.AutoSizeColumn(j); //control cell width
String columnName = data.Columns[j].ToString();
cell.SetCellValue(data.Rows[i][columnName].ToString());
}
}
else ///here has problems
{
var row = sheet1.GetRow(i);
//sheet1.RemoveRow(row);
sheet1.ShiftRows(i + 1, sheet1.LastRowNum + 1, -1);
}
}
if (num != 0)
{
//send email
}
}
}
I'm not sure why you need to resend the same file again with different contents instead of simply sending a different file, but could you perhaps try moving the creation of your sheet inside the for loop, and try removing the entire sheet instead? E.g. something like this:
private void Email()
{
//get the data from database
DataTable data = GetData();
int maxLavel = Convert.ToInt32(data.Compute("max([AssignedID])", string.Empty));
IWorkbook workbook;
workbook = new HSSFWorkbook();
for (int Emp = 0; Emp < maxLavel; Emp++)
{
ISheet sheet1 = workbook.CreateSheet("Sheet 1");
int num = 0;
//make a header row
IRow row1 = sheet1.CreateRow(0);
for (int j = 0; j < data.Columns.Count; j++)
{
ICell cell = row1.CreateCell(j);
String columnName = data.Columns[j].ToString();
cell.SetCellValue(columnName);
}
//loops through data
for (int i = 0; i < data.Rows.Count; i++)
{
IRow row = sheet1.CreateRow(i + 1);
if (Emp == Convert.ToInt32(data.Rows[i][0]))
{
num++;
for (int j = 0; j < data.Columns.Count; j++)
{
ICell cell = row.CreateCell(j);
sheet1.AutoSizeColumn(j); //control cell width
String columnName = data.Columns[j].ToString();
cell.SetCellValue(data.Rows[i][columnName].ToString());
}
}
}
if (num != 0)
{
//send email
}
workbook.remove(sheet1);
}
}
I figure it out..I don't need to remove the row.
IRow row = sheet1.CreateRow(i);
This should be changed.
for (int i = 0; i < data.Rows.Count; i++)
{
if (Emp == Convert.ToInt32(data.Rows[i][0]))
{
IRow row = sheet1.CreateRow(row_num);
num++; row_num++;
for (int j = 0; j < data.Columns.Count; j++)
{
ICell cell = row.CreateCell(j);
sheet1.AutoSizeColumn(j); //control cell width
String columnName = data.Columns[j].ToString();
cell.SetCellValue(data.Rows[i][columnName].ToString());
}
}
}
Related
My Excel has column data like
When I get the data in my asp.net api using below code, I get the data 01-1月-2021 instead of 2021-01-01 then I get the error in line entity.startTime = Convert.ToDateTime(row[0].ToString().Trim());
for (int j = 0; j < HttpContext.Current.Request.Files.Count; j++)
{
string fileName = HttpContext.Current.Request.Files[j].FileName;
if (fileName.Contains(".xlsx") || fileName.Contains(".xls"))
{
dataset = ExcelHelper.ExcelStreamToDataSet(HttpContext.Current.Request.Files[j].InputStream, HttpContext.Current.Request.Files[j].FileName);
bool isFileFind = false;
List<ExcelRowErrorInfoAssetInfo> fileErrorAllList = new List<ExcelRowErrorInfoAssetInfo>();
for (int i = 0; i < dataset.Tables.Count; i++)
{
DataTable table = dataset.Tables[i];
string sheetName = table.TableName;
#region
for (int r = 0; r < table.Rows.Count; r++)
{
DataRow row = table.Rows[r];
int cnt = row.ItemArray.ToList().Where(a => string.IsNullOrEmpty(a.ToString())).Count();
if (cnt < row.ItemArray.Count())
{
if (sheetName == "基本信息")
{
AssetsInfoMap entity = new AssetsInfoMap();
//startTime is type of DateTime
entity.startTime = Convert.ToDateTime(row[0].ToString().Trim());
entity.endTime = Convert.ToDateTime(row[1].ToString().Trim());
}
}
}
#endregion
}
public static DataSet ExcelStreamToDataSet(Stream stream, string fileName)
{
DataSet dataset = new DataSet();
int startRow = 0;
try
{
IWorkbook workbook = null;
if (fileName.IndexOf(".xlsx") > 0)
workbook = new XSSFWorkbook(stream);
else if (fileName.IndexOf(".xls") > 0)
workbook = new HSSFWorkbook(stream);
int sheetCount=workbook.NumberOfSheets;
for (int m = 0; m < sheetCount-1; m++)
{
DataTable data = new DataTable();
ISheet sheet = workbook.GetSheetAt(m);
data.TableName= sheet.SheetName;
if (sheet != null)
{
IRow firstRow = sheet.GetRow(0);
int cellCount = firstRow.LastCellNum;
for (int k = firstRow.FirstCellNum; k < cellCount; ++k)
{
ICell cell = firstRow.GetCell(k);
if (cell != null)
{
string cellValue = cell.StringCellValue;
if (cellValue != null)
{
DataColumn column = new DataColumn(cellValue);
data.Columns.Add(column);
}
}
}
startRow = sheet.FirstRowNum + 1;
int rowCount = sheet.LastRowNum;
for (int i = startRow; i <= rowCount; ++i)
{
IRow row = sheet.GetRow(i);
if (row == null) continue;
DataRow dataRow = data.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
if (row.GetCell(j) != null)
dataRow[j] = row.GetCell(j).ToString();
}
data.Rows.Add(dataRow);
}
}
dataset.Tables.Add(data);
}
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
}
return dataset;
}
}
So how to get correct data to assign it to my model, do you have any ideas based on my above code?
ICell defines a property .DateCellValue, so you should use this when mapping your date values:
ICell cell = row.GetCell(j);
if (cell.CellType == CellType.Numeric && DateUtil.IsCellDateFormatted(cell))
{
dataRow[j] = cell.DateCellValue;
}
This will now store your value as a DateTime rather than as a string. We now need to do away with your DateTime->string->DateTime conversion:
entity.startTime = (DateTime)row[0];
I am trying to get a total number of rows being used in excel using Epplus but I am unable to get an exact count and the count also includes null I need an only exact range of used cells.
these lines of code I am using
FileInfo fileinfo = new FileInfo(fileName);
ExcelPackage p = new ExcelPackage(fileinfo);
ExcelWorksheet w = p.Workbook.Worksheets[1];
int Rmax = w.Dimension.End.Row;
int Cmax = w.Dimension.End.Column;
Console.WriteLine(Rmax);
Console.WriteLine(Cmax);
You can get rows and columns from these lines
using (ExcelPackage package = new ExcelPackage(stream))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
int rowCount = worksheet.Dimension.Rows;
int colCount = worksheet.Dimension.Columns;
}
int count = Rmax * Cmax;
int firstCellValue = 0;
int lastCellValue = 0;
for (int row = 1; row <= Rmax; row++) {
for (int column = 1; column <= Cmax; column++) {
if (string.IsNullOrEmpty(worksheet.Cells[row, column].GetValue<String>())) {
count--;
}
}
}
UPDATE
int rowCount = Rmax;
int count = Rmax * Cmax;
string firstCellValue = string.Empty;
string lastCellValue = string.Empty;
for (int row = 1; row <= Rmax; row++) {
bool foundValue = false;
int leftIndex = 1;
int rightIndex = Cmax;
for (int column = 1; column <= Cmax; column++) {
if (leftIndex == rightIndex) {
if (!foundValue) {
rowCount--;
break;
}
}
if (!string.IsNullOrEmpty(worksheet.Cells[row, column].GetValue < String > ())) {
foundValue = true;
firstCellValue = worksheet.Cells[row, column].ToString();
leftIndex++;
}
if (!string.IsNullOrEmpty(worksheet.Cells[row, rightIndex].GetValue < String > ())) {
foundValue = true;
lastCellValue = worksheet.Cells[row, rightIndex].ToString();
rightIndex--;
}
}
}
Console.WriteLine("firstCellValue" + firstCellValue);
Console.WriteLine("lastCellValue" + lastCellValue);
Console.WriteLine("Number of cells" + rowCount);
I have the following code that should loop through all the rows in my DataGridView, and write all their cell values to a text file.
However, it outputs all the rows, but only the first cell of each one, and not the other three cells.
string file_name = "C:\\test1.txt";
var objWriter = new System.IO.StreamWriter(file_name);
int count = dgv.Rows.Count;
for (int row = 0; row < count; row++)
{
objWriter.WriteLine(dgv.Rows[row].Cells[0].Value.ToString());
}
objWriter.Close();
for (int row = 0; row < count; row++)
{
int colCount = dgv.Rows[row].Cells.Count;
for ( int col = 0; col < colCount; col++)
{
objWriter.WriteLine(dgv.Rows[row].Cells[col].Value.ToString());
}
// record seperator could be written here.
}
Although, it would be cleaner if you used a foreach loop.
TextWriter sw = new StreamWriter(#"D:\\file11.txt");
int rowcount = dataGridViewX1.Rows.Count;
for (int i = 0; i < rowcount - 1; i++)
{
sw.WriteLine(dataGridViewX1.Rows[i].Cells[0].Value.ToString());
}
sw.Close();
MessageBox.Show("Text file was created." );
How can I read data from DataGridView in C#? I want to read the data appear in Table. How do I navigate through lines?
something like
for (int rows = 0; rows < dataGrid.Rows.Count; rows++)
{
for (int col= 0; col < dataGrid.Rows[rows].Cells.Count; col++)
{
string value = dataGrid.Rows[rows].Cells[col].Value.ToString();
}
}
example without using index
foreach (DataGridViewRow row in dataGrid.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
string value = cell.Value.ToString();
}
}
If you wish, you can also use the column names instead of column numbers.
For example, if you want to read data from DataGridView on the 4. row and the "Name" column.
It provides me a better understanding for which variable I am dealing with.
dataGridView.Rows[4].Cells["Name"].Value.ToString();
Hope it helps.
string[,] myGridData = new string[dataGridView1.Rows.Count,3];
int i = 0;
foreach(DataRow row in dataGridView1.Rows)
{
myGridData[i][0] = row.Cells[0].Value.ToString();
myGridData[i][1] = row.Cells[1].Value.ToString();
myGridData[i][2] = row.Cells[2].Value.ToString();
i++;
}
Hope this helps....
Code Example : Reading data from DataGridView and storing it in an array
int[,] n = new int[3, 19];
for (int i = 0; i < (StartDataView.Rows.Count - 1); i++)
{
for (int j = 0; j < StartDataView.Columns.Count; j++)
{
if(this.StartDataView.Rows[i].Cells[j].Value.ToString() != string.Empty)
{
try
{
n[i, j] = int.Parse(this.StartDataView.Rows[i].Cells[j].Value.ToString());
}
catch (Exception Ee)
{ //get exception of "null"
MessageBox.Show(Ee.ToString());
}
}
}
}
private void HighLightGridRows()
{
Debugger.Launch();
for (int i = 0; i < dtgvAppSettings.Rows.Count; i++)
{
String key = dtgvAppSettings.Rows[i].Cells["Key"].Value.ToString();
if (key.ToLower().Contains("applicationpath") == true)
{
dtgvAppSettings.Rows[i].DefaultCellStyle.BackColor = Color.Yellow;
}
}
}
I have datatable and I am displaying those values in the datagridview with the helping of code :
dataGridView1.ColumnCount = TableWithOnlyFixedColumns.Columns.Count;
dataGridView1.RowCount = TableWithOnlyFixedColumns.Rows.Count;
for (int i = 0; i < dataGridView1.RowCount; i++)
{
for (int j = 0; j < dataGridView1.ColumnCount; j++)
{
dataGridView1[j, i].Value = TableWithOnlyFixedColumns.Rows[i][j].ToString();
}
}
TableExtractedFromFile.Clear();
TableWithOnlyFixedColumns.Clear();
Now I want to save the records in the datatable in csv file.How can I do that ?
You could do this:
// we'll use these to check for rows with nulls
var columns = yourTable.Columns
.Cast<DataColumn>();
// say the column you want to sort by is called "Date"
var rows = yourTable.Select("", "Date ASC"); // or "Date DESC"
using (var writer = new StreamWriter(yourPath)) {
for (int i = 0; i < rows.Length; i++) {
DataRow row = rows[i];
// check for any null cells
if (columns.Any(column => row.IsNull(column)))
continue;
string[] textCells = row.ItemArray
.Select(cell => cell.ToString()) // may need to pick a text qualifier here
.ToArray();
// check for non-null but EMPTY cells
if (textCells.Any(text => string.IsNullOrEmpty(text)))
continue;
writer.WriteLine(string.Join(",", textCells));
}
}