Добавление стиля к столбцам, которые написаны индивидуально в таблицу Excel

Я пытаюсь объяснить эту проблему шаг за шагом в следующем примере.

0) Question

Я пытаюсь спросить вас вот так:

я хочу чтобы открыть страницу, например, facebook profile www.facebook.com/kaila.piyush

, получить идентификатор от url и проанализировать его на файл profile.php и вернуть данные из базы данных и показать пользователю его профиль

обычно, когда мы разрабатываем любой веб-сайт, его ссылка выглядит как www.website.com/profile.php?id=username example.com/weblog/index.php?y=2000&m=11&d=23&id = 5678

Теперь мы обновляем новый стиль, не переписываем, мы используем www.website.com/username или example.com/weblog/2000/11/23/5678 как permalink

http://example.com/profile/userid (get a profile by the ID) 
http://example.com/profile/username (get a profile by the username) 
http://example.com/myprofile (get the profile of the currently logged-in user)

1) .htaccess

Создайте файл .htaccess в корневой папке или обновите существующий:

Options +FollowSymLinks
# Turn on the RewriteEngine
RewriteEngine On
#  Rules
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php

Что это делает?

Если запрос предназначен для реального каталога или файла (который существует на сервере), index.php не обслуживается, иначе каждый URL перенаправляется на index.php.

2) index.php

Теперь мы хотим знать, что t для запуска, поэтому нам нужно прочитать URL:

В index.php:

// index.php    

// This is necessary when index.php is not in the root folder, but in some subfolder...
// We compare $requestURL and $scriptName to remove the inappropriate values
$requestURI = explode(‘/’, $_SERVER[‘REQUEST_URI’]);
$scriptName = explode(‘/’,$_SERVER[‘SCRIPT_NAME’]);

for ($i= 0; $i < sizeof($scriptName); $i++)
{
    if ($requestURI[$i] == $scriptName[$i])
    {
        unset($requestURI[$i]);
    }
}

$command = array_values($requestURI);
With the url http://example.com/profile/19837, $command would contain :

$command = array(
    [0] => 'profile',
    [1] => 19837,
    [2] => ,
)
Now, we have to dispatch the URLs. We add this in the index.php :

// index.php

require_once("profile.php"); // We need this file
switch($command[0])
{
    case ‘profile’ :
        // We run the profile function from the profile.php file.
        profile($command([1]);
        break;
    case ‘myprofile’ :
        // We run the myProfile function from the profile.php file.
        myProfile();
        break;
    default:
        // Wrong page ! You could also redirect to your custom 404 page.
        echo "404 Error : wrong page.";
        break;
}

2) profile.php

Теперь в profile.php, мы должны иметь что-то вроде этого:

// profile.php

function profile($chars)
{
    // We check if $chars is an Integer (ie. an ID) or a String (ie. a potential username)

    if (is_int($chars)) {
        $id = $chars;
        // Do the SQL to get the $user from his ID
        // ........
    } else {
        $username = mysqli_real_escape_string($char);
        // Do the SQL to get the $user from his username
        // ...........
    }

    // Render your view with the $user variable
    // .........
}

function myProfile()
{
    // Get the currently logged-in user ID from the session :
    $id = ....

    // Run the above function :
    profile($id);
}
1
задан MaxB 11 March 2019 в 12:31
поделиться

1 ответ

Я думаю, что вы можете попробовать использовать двойные скобки [[]] для вызова этого в кадре данных или использовать параметр subset в applymap(), как показано ниже :

df[['Name']].style.applymap(color_green).to_excel(path,index=False)

Другой путь будет таким:

df.style.applymap(color_green, subset=pd.IndexSlice[:, ['Name']])

это приводит к полному фрейму данных, оформленному в виде списка определенных столбцов.

Для лучшего понимания, пример ниже:

Демо:

Давайте рассмотрим следующий df:

   Name  some_col
0    abc         1
1  CHECK         1
2   defg         2
3  CHECK         3
4    efg         3
5    ijk         3
6    lmn         1
7    opq         7

def color_green(val):
    color = 'green' if val != 'CHECK' else 'black'
    return 'color: %s' % color
df[['Name']].style.applymap(color_green)

это выводит

enter image description here

второй метод:

[113 ]

выводит:

enter image description here

Затем вы можете экспортировать это в Excel.

Надеюсь, это поможет.

0
ответ дан anky_91 11 March 2019 в 12:31
поделиться
Другие вопросы по тегам:

Похожие вопросы: